How to retrieve checkboxes values in jQuery

lanqy picture lanqy · Apr 24, 2009 · Viewed 593.6k times · Source

How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?

Just like this code:

<html>
  <head>
  </head>

  <body>
    <div id="c_b">
      <input type="checkbox" value="one_name" checked>
      <input type="checkbox" value="one_name1">
      <input type="checkbox" value="one_name2">
    </div>  

    <textarea id="t"></textarea>
  </body>
</html>

If the id="c_d" is updated by Ajax, the below of altCognito's code doesn't work. Is there any good solution?

Answer

cgp picture cgp · Apr 24, 2009

Here's one that works (see the example):

 function updateTextArea() {         
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });
     $('#t').val(allVals);
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

Update

Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.