get checkbox list value using jquery



In this section, We will get the values of selected checkboxes in a group using JQuery.

Here we are using :ckecked selector for checking which checkboxes are checked. Then combine with each() method to check all the checkboxes selected in a group like for loop. Here the each() method used here simply iterates over all the checkboxes that are checked. Here's an example:

<div class="row">
<div class="col-md-12">
<strong>Habits: </strong>
</div>
<div class="col-md-3">
<label style="display: inline;">Tea <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Tea" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Coffee <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Coffee" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Cold Drink <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Cold Drink" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Smoking <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Smoking" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Alcohol <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Alcohol" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Drug Addiction <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Drug Addiction" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Zarda <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Zarda" /></label>
</div>
<div class="col-md-3">
<label style="display: inline;">Pan Masala <input name="habits" style="height: 17px; width: 20%;" type="checkbox" value="Pan Masala" /></label>
</div>
</div>
<div class="col-md-4 col-md-offset-4">
<input class="btn btn-primary" id="add" type="button" value="Submit" />
</div>

Put this above HTML coding in your html <body></body> tag.

Then in <head></head> tag write jquery for getting all selected values. Follow the below steps:


<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
var habits = [];
$.each($("input[name='habits']:checked"), function () {
habits.push($(this).val());
});
alert('Your Habits are :'+habits.join(", "));
})
})
</script>


Add jquery package in your solution and give that script reference in your HTML page. Like below script reference

<script src="~/Scripts/jquery-3.0.0.min.js"></script>

Otherwise you can add direct link of jquery script reference file. Like below script reference

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

Follow this above procedure in your HTML page and you will get your required result.
output:



Post a Comment

0 Comments