Tuesday, February 4, 2014

Checkboxes Capture and Display using jQuery

I was asked the other day how to capture and display a collection of checkbox values.  I'm grateful for the internet and Stack Overflow for these two posts: capture and display.   Here is the abridged version:

The checkboxes
 
<div id='list'>
    <input type='checkbox' value='1' />
    <input type='checkbox' value='2' />
    <input type='checkbox' value='3' />
    <input type='checkbox' value='4' />
    <input type='checkbox' value='5' />
    <input type='checkbox' value='6' />
    <input type='checkbox' value='7' />
    <input type='checkbox' value='8' />
    <input type='checkbox' value='9' />
    <input type='checkbox' value='10' />
</div>


Capturing
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});


Displaying

$("#list").find('[value=' + values.join('], [value=') + ']').prop("checked", true);


No comments: