Get Selected Checkboxes Id Using jQuery(Single Selection Only)
The single selected checkboxes allow selecting only one checkbox at a time. get selected checkboxes id on click of the button. See the below example to find how to get single selected checkbox id.
| <script> $(document).ready(function(){ $('input[name="cricket"]').on('change', function() { $('input[name="cricket"]').not(this).prop('checked', false); alert("The best cricketer is: " + $('input[name="cricket"]:checked').attr("id")); }); }); </script> <form> <input type="checkbox" name="cricket" value="Virat Kohli" class="mycheck"> Virat Kohli <input type="checkbox" name="cricket" value="Chris Gayle" class="mycheck"> Chris Gayle <input type="checkbox" name="cricket" value="Mahendra Singh Dhoni" class="mycheck"> Mahendra Singh Dhoni <input type="checkbox" name="cricket" value="Sachin Tendulkar" class="mycheck"> Sachin Tendulkar <input type="checkbox" name="cricket" value="Donald Bradman" class="mycheck"> Donald Bradman </form> |
Output
You have to select one checkbox, click any checkbox given above to get its id. You are allowed to select the only single checkbox at once.
Get Multiple Selected Checkboxes Id Using jQuery
If you want to find the ids for the multiple selected checkboxes. Find the ids of selected checkboxes and get it array format. See the example below to get the ids of all the selected checkboxes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <script> $(document).ready(function(){ $('#btnMultiple').click(function(){ var cricketer = []; $("input:checkbox[name='cricketer']:checked").each(function(){ cricketer.push($(this).attr("id")); }); alert("The best cricketers are: " + cricketer.join(", ")); }); }); </script> <form> <input type="checkbox" name="cricketer" value="Virat Kohli" class="mycheck"> Virat Kohli <input type="checkbox" name="cricketer" value="Chris Gayle" class="mycheck"> Chris Gayle <input type="checkbox" name="cricketer" value="Mahendra Singh Dhoni" class="mycheck"> Mahendra Singh Dhoni <input type="checkbox" name="cricketer" value="Sachin Tendulkar" class="mycheck"> Sachin Tendulkar <input type="checkbox" name="cricketer" value="Donald Bradman" class="mycheck"> Donald Bradman <button type="button" class="btn btn-primary" id="btnMultiple">Get Multiple Id</button> </form> |
Output
Click multiple checkboxes and get its ids in an array format. The above example is used to get multiple ids and use it in other ways.
No comments:
Post a Comment