How to get the values of selected check boxes in a collection using jQuery
Get the values of selected check boxes using jQuery
In the below scenario we have used jQuery each loop and join function, with the help of these we can get selected values of check boxes.
HTML -
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" value="football" name="sport"> Football</label>
<label><input type="checkbox" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" value="swimming" name="sport"> Swimming</label>
<br>
<input type="button" id="getValues" value="Get Values">
Code -
$(document).ready(function() {
$("#getValues").click(function(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
});
alert("My favorite sports are: " + favorite.join(", "));
});
});
Output -
If you have selected football, baseball and racing the your output will be as shown below -
My favorite sports are: football, baseball, racing
Comments
Post a Comment