1

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.

Matt
  • 1,265
  • 1
  • 16
  • 24

4 Answers4

2

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?

Community
  • 1
  • 1
Mahes
  • 3,938
  • 1
  • 34
  • 39
1

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.

James Johnson
  • 45,496
  • 8
  • 73
  • 110
0

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')); 
    });
});
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • see Mahes answer. Unfortunately the attribute "DataValueField" doesn't render in html. – Matt Oct 23 '11 at 21:04
0
$('#<%= 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.

PCasagrande
  • 5,302
  • 3
  • 27
  • 36