Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to get values of selected checkboxes in jquery?

Hi I am developing jquery application with asp.net. I have list of checkboxes as below. If i check any checkbox then i want to display it. Below is my checkboxlist.

  <asp:CheckBoxList ID="ChKResons" runat="server" RepeatColumns="1" RepeatDirection="Horizontal" Style="margin-bottom: 8px; margin-right: 5px;" CellPadding="5" CellSpacing="25">
                        <asp:ListItem Text="Your financial offer exceeded our budgeted amount" value="1"/>
                        <asp:ListItem Text="Your technical offer didn't comply with Oman Air's technical requirement" Value="2" />
                    </asp:CheckBoxList>

This is my jquery code.

 $('#ChKResons').on('click', ':checkbox', function () {
        if ($(this).is(':checked')) {
            // handle checkbox check
            alert($(this).val());
        } else {
            // checkbox is unchecked
            alert('unchecked')
        }
    });
    $('#ChKResons :checkbox').live('click', function () {
        alert($(this).is(':checked'));
    });

Above code does not work. May i get some help to sort out this? An help would be appreciated. Thank you.

Upvotes: 0

Views: 51

Answers (2)

MicroPyramid
MicroPyramid

Reputation: 1630

In general checkboxes will be having change event. So it is good practice using change rather than click. Ofcourse click will also work.

$("input:checkbox").change(function () {
    if($(this).prop("checked")){
       alert('checked');
    }else{
       alert("unchecked");
    }
});

Upvotes: 0

Programmer
Programmer

Reputation: 443

Use

$(this).prop('checked') 

instead of

$(this).is(':checked')

If your generated HTML checkboxes have id ChKResons then please add an event using id only like:

$('#ChKResons').on('click', function () {
    alert($(this).prop('checked'));
});

Attach the event only once. And if you have multiple elements with the same id, then remove the id and add a common class on all elements and attach an event on the class selector.

$('.commonClass').on('click', function () {
    alert($(this).prop('checked'));
});

Upvotes: 2

Related Questions