I want to get the values of checked checkboxes with the name="car_type[]"
and alert the final array with all the values. How to do that? So far, I have this code. But it's not working. I don't know how to loop through checked checkboxes properly and add the values to the array car_type_arr
. I also cannot alert the final array using alert(car_type_arr);
. Thanks for any help.
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]:checked").each(function()
{
// here I need to add values to array like in php
// e.g. $car_type_arr[] = $the_grabbed_value;
// but using javascript syntax
// How to do that?
});
// then I need to alert the array, how to do that in JS?
alert(car_type_arr);
return false;
});
});
You can use map
var car_type_arr = $("input:checkbox[name=car_type]:checked").map(function() {
return this.value;
}).get();
console.log(car_type_arr);
$("input:checkbox[name=car_type]:checked").each(function() {
car_type_arr.push($(this).val());
});
Try this:
$("input:checkbox[name=car_type]:checked").each(function()
{
car_type_arr.push($(this).val());
});
Try below code:
<input type="checkbox" name="chkBox" value="xxx">
<input type="checkbox" name="chkBox" value="xxx1">
<input type="checkbox" name="chkBox" value="xxx2">
<input type="button" id="btnBox">
$(document).ready(function(){
$("#btnBox").click(function(){
var car_type_arr = [];
$("input:checkbox[name=chkBox]:checked").each(function() {
car_type_arr.push($(this).val());
alert(car_type_arr);
});
});
});
your code should look like,
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]").each(function()
{
if($(this).is(':checked')){
car_type_arr.push($(this).val());
}
});
alert(car_type_arr);
return false;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.