Niranjan Godbole Niranjan Godbole - 4 years ago 73
Javascript Question

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.

Answer Source

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'));
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download