In this post we are going to see how to get all the checked checkboxes using jQuery. Some time in asp.net applications we need to do operations at client side on controls like checkboxes, dropdown list, buttons…etc. Here we will see how to access checkboxes at client side using jQuery and how to get checked checkboxes. To get the checked checkboxes, jQuery provides selector :checked.
Sample code to get all checked checkboxes[jQuery – ASP.Net]
<input value="1" checked type="checkbox" name="numbers" />
<input value="2" type="checkbox" name="numbers" />
<input value="3" checked type="checkbox" name="numbers" />
Now to get only the checked checkboxes we will use below line of code that will store all the checked checkboxes as an array.
$checkedCheckboxes = $("input:checkbox[name=numbers]:checked");;
We can iterate though the checked checkbox array using .each and perform some operations or can get or set values to checkboxes.
var selectedValues="";
$checkedCheckboxes.each(function () {
selectedValues += $(this).val() +",";
});
);
Let's put all above code togather
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
var selectedValues="";
$checkedCheckboxes = $("input:checkbox[name=numbers]:checked");
$checkedCheckboxes.each(function () {
selectedValues += $(this).val() +",";
});
alert(selectedValues);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input value="1" checked type="checkbox" name="numbers" />
<input value="2" type="checkbox" name="numbers" />
<input value="3" checked type="checkbox" name="numbers" />
</div>
</form>
</body>
</html>
//Output //1,3
Better without last comma:
ReplyDeletevar vals = [];
$('input:checkbox[name=numbers]:checked').each(function() {
vals.push($(this).val());
});
Yes using array can be alternative option to store checked check box's. But it depends do you need comma separated string do you need array to store values.
ReplyDeleteI use the array push code commented above and then if I need a comma-separated string I just use:
ReplyDeletestr = vals.join(',');