HOWTO: Checkbox event listener
Sample form code:
<?php
drupal_add_js('foobar.js');
$form['foobar_A_check'] = array(
'#type' => 'checkbox',
'#prefix' => '<div class="foobar_A_group">',
);
$form['foobar_A_text'] = array(
'#type' => 'textfield',
'#suffix' => '</div>'
);
?>Drupal will generate HTML like the following:
<div class="foobar_A_group">
<div class="form_item">
<input type="checkbox" value="Check me!" />
</div>
<div class="form_item">
<input type="text" value="" />
</div>
</div>Sample jQuery Javascript file (foobar.js)
if (Drupal.jsEnabled) {
$(document).ready(function () {
$("div.foobar_A_group/div.form_item).each(function(){
$(this).children("input:checkbox").click(function(){
message = (this.checked) ? "message1" : "message2";
$(this).parents().siblings().children("input:text").val(message);
});
});
});
}Of course there are simpler ways of doing this, but this code comes in handy when the naming of the checkbox/textfield are dynamic and you do not know the id values.
The code loops through the document, finding all DIVs with classname "form_item" that are descendants of DIVs with classname "foobar_A_group". It then finds the child INPUT element whose type is "checkbox", and adds a click (onmouseclick) event listener to it which will change the message according to whether or not the box is checked. It then traverses up to its parents' siblings' children (cousin) changing the value of the INPUT element of type "text".
