jQuery Get Selected Checkbox Values with Comma Separated List on Name


Here I will explain how to use jQuery to get checked / selected checkbox values with comma separated list based on name.

Description:

In previous articles I explained jQuery Get Set Delete Cookie example, jQuery Show gridview row details on mouseover, jQuery Create simple mobile website, jQuery clear textbox value on focus, jQuery Draggable & Resizable div with example and many articles relating to JQuery, JavaScript, asp.net, code snippets. Now I will explain how to get selected checkbox values with comma separated list based on name in jQuery.

Get selected checkbox values in jQuery

To get selected checkbox values based on name we need to write the code like as shown below

var slvals = []
$('input:checkbox[name=nameofyourcheckbox]:checked').each(function() {
slvals.push($(this).val())

If you want to see it in complete example check below code

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$('#btnSubmit').click(function() {
var slvals = []
$('input:checkbox[name=chkcountry]:checked').each(function() {
slvals.push($(this).val())
})
alert('Selected Checkbox values are: ' + slvals)
})
});
</script>
</head>
<body>
<b>Sample checkbox inputs :</b>
<input type="checkbox" name="chkcountry" id="chkindia" value="India" />India
<input type="checkbox" name="chkcountry" id="chkusa" value="USA" />USA
<input type="checkbox" name="chkcountry" id="chkAustralia" value="Australia" />Australia
<input type="checkbox" name="chkcountry" id="chkMalaysia" value="Malaysia" />Malaysia
<button id="btnSubmit">Get Selected Values</button>
</body>
</html>

Comments