Search code examples
eventscheckboxclickprototypejs

Prototype function to set onclick event observer in checkboxes


I want to set an observer for each of the following checkboxes:

<div id="listr">
  <ul id="lr" style="list-style-type: none">
    <p class="tir">Text 1</p>
    <li class="ro"><input type="checkbox" name="r1" id="r1"/>A1</li>
    <li class="ro"><input type="checkbox" name="r2" />A2</li>
    <p class="tir">Text 2</p>
    <li class="rubro"><input type="checkbox" name="r3" />B1</li>
    <p class="tir">Text 3</p>
    <li class="ro"><input type="checkbox" name="r4" />B2</li>
  </ul>
</div>

It works if I write one observer per checkbox, but I want to do it in a short fashion, so I need something like

$$('listr.lr.li.input').invoke('observe',click,function(field) {
    alert(this.name + ' clicked ' + this.checked);
    // other stuff ...
});

Which is not working

Thanks in advance


Solution

  • Try using a valid CSS3 selector:

    $$('#listr input[type="checkbox"]').invoke('observe','click',function(field) {
        alert(this.name + ' clicked ' + this.checked);
        // other stuff ...
    });
    

    http://prototypejs.org/doc/latest/dom/dollar-dollar/