Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select values of checkbox group with jQuery

I'm using Zend_Form to output a set group of checkboxes:

<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label> 

With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:

$("input[@name='user_group[]']").val() 

but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?

like image 500
dragonmantank Avatar asked Jan 06 '09 14:01

dragonmantank


People also ask

How check group checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How can I store multiple checkbox values in jQuery?

Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.


1 Answers

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked") 

With those checked items, you can either create a collection of those values or do something to the collection:

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 }); 
like image 59
patridge Avatar answered Sep 22 '22 20:09

patridge