Posted
Here's an example of a script to hide a textarea or a text input based on a checkbox setting.
Working with a single checkbox + textarea pair
See a demo {rokbox text=|here| size=|600,600| }http://greyhead.org/index.php?option=com_chronoforms&chronoform=demo_hidden_textarea&tmpl=component{/rokbox}
The form uses standard ChronoForms elements with IDs set - 'checkbox' for the checkbox and 'textarea' for the textarea. If you use different IDs you can change the two lines near the beginning of the script. The text area is set as 'required' on the validation tab.
This is the JavaScript that is added in a Load JS action in the form On Load event:
var checkbox_id, textarea_id, checkbox, textarea, div; /* edit the next two lines to match the ids of the elements in your form */ checkbox_id = 'checkbox'; textarea_id = 'textarea'; window.addEvent('domready', function() { checkbox = $(checkbox_id); textarea = $(textarea_id); div = $(textarea_id+'_container_div'); div.dissolve(); showHide(); checkbox.addEvent('click', showHide); }); function showHide() { if ( checkbox.checked ) { div.reveal(); textarea.disabled = false; } else { div.dissolve(); textarea.value = ''; textarea.disabled = true; } }
Working with more than one checkbox + textarea pair
A few days after I wrote this FAQ a user wanted to make it work with a form where there was more than one checkbox + textarea pair. And in that case is doesn't work :-(
Here is the code for a more advanced version that will work with as many pairs as you like.
var checkboxes; window.addEvent('domready', function() { var i, checkbox, textarea, div, textbox; checkboxes = {}; // link the checkboxes and textarea ids here checkboxes['checkbox_1'] = 'textarea_1'; checkboxes['checkbox_2'] = 'textarea_2'; checkboxes['checkbox_3'] = 'textarea_3'; for ( i in checkboxes ) { checkbox = $(i); textbox = $(checkboxes[i]); div = $(textbox.id + '_container_div'); div.dissolve(); showHide(i); addEventToCheckbox(checkbox); } function addEventToCheckbox(checkbox) { checkbox.addEvent('click', function(event) { showHide(event.target.id); }); } }); function showHide(id) { var checkbox, textarea, div; if(typeof id == 'undefined') { return; } checkbox = $(id); textarea = checkboxes[id]; div = $(textarea + '_container_div'); textarea = $(textarea); if(checkbox.checked) { div.setStyle('display', 'block'); //div.reveal(); div.setStyle('display', 'block'); textarea.disabled = false; } else { div.setStyle('display', 'none'); //div.dissolve(); textarea.value = ''; textarea.disabled = true; } }
Notes:
- I couldn't get the dissolve and reveal to work with this code so replaced them with the two setStyle() lines. By all means test either version on your site.
- Although this refers to text areas the code will work with Text input elements and can probably be adapted to work with other elements with minor changes.
- I've used the id's checkbox_1 and textarea_1 but you can replace these with any valid ids from your form.