How can I get the value of checkboxes which are selected using jquery? My html code is as follows:
You can get them like this
$('#save_value').click(function() {
$('.ads_Checkbox:checked').each(function() {
alert($(this).val());
});
});
jsfiddle
You can do it like this,
$('.ads_Checkbox:checked')
You can iterate through them with each()
and fill the array with checkedbox values.
Live Demo
To get the values of selected checkboxes in array
var i = 0;
$('#save_value').click(function () {
var arr = [];
$('.ads_Checkbox:checked').each(function () {
arr[i++] = $(this).val();
});
});
Edit, using .map()
You can also use jQuery.map with get()
to get the array of selected checkboxe values.
As a side note using this.value
instead of $(this).val()
would give better performance.
Live Demo
$('#save_value').click(function(){
var arr = $('.ads_Checkbox:checked').map(function(){
return this.value;
}).get();
});
Try this, jQuery how to get multiple checkbox's value
For Demo or more Example
$(document).ready(function() {
$(".btn_click").click(function(){
var test = new Array();
$("input[name='programming']:checked").each(function() {
test.push($(this).val());
});
alert("My favourite programming languages are: " + test);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values of Selected Checboxes</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<h3>Select your favorite Programming Languages :</h3>
<label><input type="checkbox" value="PHP" name="programming"> PHP</label>
<label><input type="checkbox" value="Java" name="programming"> Java</label>
<label><input type="checkbox" value="Ruby" name="programming"> Ruby</label>
<label><input type="checkbox" value="Python" name="programming"> Python</label>
<label><input type="checkbox" value="JavaScript" name="programming"> JavaScript</label>
<label><input type="checkbox" value="Rust" name="programming">Rust</label>
<label><input type="checkbox" value="C" name="programming"> C</label>
<br>
<button type="button" class="btn_click" style="margin-top: 10px;">Click here to Get Values</button>
</form>
</body>
</html>
Since u have the same class name against all check box, thus
$(".ads_Checkbox")
will give u all the checkboxes, and then you can iterate them using each loop like
$(".ads_Checkbox:checked").each(function(){
alert($(this).val());
});
$('input:checked').map(function(i, e) {return e.value}).toArray();
Also you can use $('input[name="selector[]"]').serialize();
. It returns URL encoded string like: "selector%5B%5D=1&selector%5B%5D=3"