Matt
Matt

Reputation: 1265

Get the values of selected checkboxes from an asp checkboxlist in jquery

I am trying to get the selected value (or values) of the checkboxlist. My problem is that I am binding the checkboxlist in c# and it's not rendering with the "Value" attribute as it would if I were to hard code the

<asp:ListItem Value=".." .. />

My checkboxlist looks like this:

<asp:CheckBoxList runat="sever" ID="cblStuff" DataValueField="myID" DataTextField="myName"></asp:CheckBoxList>

So when I try to use jquery and do the follow, it returns only "on" as apposed to "myID". Am I missing something? I was under the impression that is what the DataValueField was for? Here is the js I am using:

$("checkboxlist selector").change(function() {
      $(this).find(":checked").each(function() { alert($(this).val()); });
});

Thanks.

Upvotes: 1

Views: 4263

Answers (4)

PCasagrande
PCasagrande

Reputation: 5412

$('#<%= checkboxlist.ClientID %> input:checkbox').change(function () {
if ($(this).is(":checked") && $(this).val() == "DesiredValue")
        alert($(this).val());
});

This will check to see if the value has been set to DesiredValue. The event fires whenever the value is changed. You must check to make sure that the item causing the event to fire is checked, and if it is if it has the value you care about.

Upvotes: 0

James Johnson
James Johnson

Reputation: 46067

You should be able to get all of the checked items like this:

$("#<%=cblStuff.ClientID%> input[type=checkbox]:checked").each(function(){
    var val = $(this).attr("value");
});

I don't think the CheckBox control has a value attribute by default, but the CheckBoxList might. In either case, you can always add a value attribute.

Upvotes: 1

Mahes
Mahes

Reputation: 4135

DataValueField is server side property and it will not be rendered in html , so you cannot get the value with jquery or any other client side code.

also check the related question: Where are the DataValueField values for a CheckBoxList stored?

Upvotes: 2

Blazemonger
Blazemonger

Reputation: 92983

You can use jQuery's attr() method to get any attribute, official or otherwise:

$("checkboxlist selector").change(function() {
    $(this).find(":checked").each(function() {
        alert($(this).attr('DataValueField')); 
    });
});

Upvotes: 0

Related Questions