Sunday 25 December 2022

Get ids of all selected checkboxes using name in jQuery

 Below code snippet explains how to find all HTML input checkboxes that are checked or selected using jQuery.

<input type="checkbox" id="Checkbox1" name = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" name = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" name = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" name = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />
 
<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $("#demo").live("click"function () {
        $("input:checkbox[name=chk]:checked").each(function () {
            alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
        });
    });
</script>
 
 
Explanation:
In the above example a click event handler has been assigned to the HTML input button. When the button is clicked, jQuery finds all the checkboxes with name “chk” and that are checked using input:checkbox[name=chk]:checked selector and then the Id and value attribute of the all checked or selected HTML input checkboxes are displayed in alert using jQuery.

No comments:

Post a Comment