Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all selected checkboxes in an array

So I have these checkboxes:

<input type="checkbox" name="type" value="4" /> <input type="checkbox" name="type" value="3" /> <input type="checkbox" name="type" value="1" /> <input type="checkbox" name="type" value="5" /> 

And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.

My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.

Any thoughts?

Edit: I would only want the selected checkboxes to be added to the array

like image 405
Ali Avatar asked Feb 26 '09 10:02

Ali


People also ask

How do you store a selected checkbox value in an array?

Inside the GetSelected function, first the HTML Table is referenced and then all the CheckBoxes inside it are referenced. Then a loop is executed over the referenced CheckBoxes and inside the loop the value of the selected (checked) CheckBox is inserted into an Array.


2 Answers

Formatted :

$("input:checkbox[name=type]:checked").each(function(){     yourArray.push($(this).val()); }); 

Hopefully, it will work.

like image 186
ybo Avatar answered Sep 28 '22 02:09

ybo


Pure JS

For those who don't want to use jQuery

var array = [] var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')  for (var i = 0; i < checkboxes.length; i++) {   array.push(checkboxes[i].value) } 
like image 36
Chris Underdown Avatar answered Sep 28 '22 03:09

Chris Underdown