Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox list values with jQuery

In a div, I have some checkbox. I'd like when I push a button get all the name of all check box checked. Could you tell me how to do this ?

<div id="MyDiv"> .... <td><%= Html.CheckBox("need_" + item.Id.ToString())%></td> ... </div> 

Thanks,

like image 645
Kris-I Avatar asked Aug 17 '09 12:08

Kris-I


2 Answers

$(document).ready(function() {     $('#someButton').click(function() {         var names = [];         $('#MyDiv input:checked').each(function() {             names.push(this.name);         });         // now names contains all of the names of checked checkboxes         // do something with it     }); }); 
like image 79
TM. Avatar answered Sep 20 '22 19:09

TM.


Since nobody has mentioned this..

If all you want is an array of values, an easier alternative would be to use the .map() method. Just remember to call .get() to convert the jQuery object to an array:

Example Here

var names = $('.parent input:checked').map(function () {     return this.name; }).get();  console.log(names); 

var names = $('.parent input:checked').map(function () {      return this.name;  }).get();    console.log(names);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="parent">      <input type="checkbox" name="name1" />      <input type="checkbox" name="name2" />      <input type="checkbox" name="name3" checked="checked" />      <input type="checkbox" name="name4" checked="checked" />      <input type="checkbox" name="name5" />  </div>

Pure JavaScript:

Example Here

var elements = document.querySelectorAll('.parent input:checked'); var names = Array.prototype.map.call(elements, function(el, i) {     return el.name; });  console.log(names); 

var elements = document.querySelectorAll('.parent input:checked');  var names = Array.prototype.map.call(elements, function(el, i){      return el.name;  });    console.log(names);
<div class="parent">      <input type="checkbox" name="name1" />      <input type="checkbox" name="name2" />      <input type="checkbox" name="name3" checked="checked" />      <input type="checkbox" name="name4" checked="checked" />      <input type="checkbox" name="name5" />  </div>
like image 22
Josh Crozier Avatar answered Sep 18 '22 19:09

Josh Crozier