February 11, 2009

get selected dynamically from list

i.e., dynamically updated list of checked choices in a simple list of checkboxes and their labels.

(note to self...)

assumed (h)tml structure:
- divs with a certain class, containing inputs and labels
- inputs of checkbox type
- labels attached to the checkboxes

f.ex:

(h)tml:

<div id="updatedList" style="float: left; width: 150px;" />

<div id="column2" style="margin-left: 155px; " />

  <div class="box">
     <input type="checkbox" id="c1" onclick="updateList()">
     <label for="c1">Checkbox 1</label>
  </div>
  <div class="box">
     <input type="checkbox" id="c2" onclick="updateList()">
     <label for="c2">Checkbox 2</label>
  </div>

</div>

js (w/prototype):

Event.observe(window, 'load', updateList);

function updateList() {
   var sel=[]; //selected list elements
   var all=$$('div.box'); //all list elements, in form of enclosing divs
   all.each(
     function (e) {
       if (e.down('input').checked == true)
         sel.push('<br />' + e.down('label').innerHTML);
     }
   );
   $('updatedList').update(sel);
}

No comments: