I am trying to get the results from a form - in particular a multicheckbox.
So I want to get the results as a simple array
[2,4,6,5,7]
I've tried these -
$('.ids:checked').serialize()
$('.ids:checked').serializeArray()
Use jQuery map() method to generate the collection and get it as an array using get() method.
$('.ids:checked').map(function(){
// return the value, which would be the collection element
return this.value;
// get it as an array
}).get()
$("button").click(function() {
console.log($('input:checked').map(function() {
return this.value;
}).get());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="bla1" value="something1">
<input type="checkbox" name="bla2" value="something2">
<input type="checkbox" name="bla3" value="something3">
<input type="checkbox" name="bla4" value="something4">
<input type="checkbox" name="bla5" value="something5">
<input type="checkbox" name="bla6" value="something6">
</form>
<button>
Click
</button>
jQuery.map() method to iterate and generate array where first argument in callback refers to the element.
$.map($('.ids:checked'),function(ele){
// return the value, which would be the array element
return ele.value;
});
$("button").click(function() {
console.log($.map($('input:checked'), function(ele) {
return ele.value;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="bla1" value="something1">
<input type="checkbox" name="bla2" value="something2">
<input type="checkbox" name="bla3" value="something3">
<input type="checkbox" name="bla4" value="something4">
<input type="checkbox" name="bla5" value="something5">
<input type="checkbox" name="bla6" value="something6">
</form>
<button>
Click
</button>
var myArray = Array.prototype.map.call($('.ids:checked'), function(item){return item.value;});
use the core js array map method and binds it to your jquery object
this won't be what you think it is if you're using the native Array.prototype.map!Array.prototype.map pass the object to the callback as argument (...map(function(item) {/* use item */})). jQuery.map bind the object to the this keyword of the callback. You are using Array.prototype.map but using the callback of jQuery.map!