5

I have this CheckBoxList on a page:

<asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource"
   datatextfield="CountryName" datavaluefield="CountryCode" />

I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don't appear to be available on the client side. The HTML output looks like this:

<table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;">
<tr>
    <td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td>
</tr>

The values ("cd", "cg", "ga", etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?

Herb Caudill
  • 50,043
  • 39
  • 124
  • 173

9 Answers9

15

I finally have the answer I've been looking for!

The asp.net CheckboxList control does in fact render the value attribute to HTML - it has been working for me in a Production site for over a year now! (We ALWAYS have EnableViewState turned off for all our sites and it still works, without any tweaks or hacks)

However, all of a sudden, it stopped working one day, and our CheckboxList checkboxes no longer were rendering their value attribute in HTML! WTF you say? So did we! It took a while to figure this out, but since it had been working before, we knew there had to be a reason. The reason was an accidental change to our web.config!

<pages controlRenderingCompatibilityVersion="3.5">

We removed this attribute from the pages configuration section and that did the trick!

Why is this so? We reflected the code for the CheckboxList control and found this in the RenderItem method:

if (this.RenderingCompatibility >= VersionUtil.Framework40)
{
    this._controlToRepeat.InputAttributes.Add("value", item.Value);
}

Dearest dev brothers and sisters do not despair! ALL the answers I searched for here on Stackexchange and the rest of the web gave erroneous information! As of .Net 4.0 asp.net renders the value attribute of the checkboxes of a CheckboxList:

<input type="checkbox" value="myvalue1" id="someid" />

Perhaps not practically useful, Microsoft gave you the ability to add a "controlRenderingCompatibilityVersion" to your web.config to turn this off by setting to a version lower than 4, which for our purposes is completely unnecessary and in fact harmful, since javascript code relied on the value attribute...

We were getting chk.val() equal to "on" for all our checkboxes, which is what originally alerted us to this problem in the first place (using jquery.val() which gets the value of the checkbox. Turns out "on" is the value of a checkbox that is checked... Learn something every day).

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
AdamE
  • 606
  • 6
  • 11
  • PLEASE do not ask people to vote/accept your answer. [Meta post regarding flagging such comments](http://meta.stackexchange.com/questions/167155/comments-asking-for-upvotes) – Andrew Barber Feb 22 '13 at 18:52
  • 2
    I know this is soooo old question, but is saved hair on my head. I've been tearing my hair out for 4 hours because of this. Thanks to this tiny change everything works. THIS IS THE BEST ANSWER FOR THIS QUESTION! – Misiu Feb 01 '14 at 14:51
  • 1
    does removing the controlRenderingCompatibilityVersion attribute have any side effects on other .NET components? – Eakan Gopalakrishnan Feb 23 '15 at 14:39
  • @EakanGopalakrishnan see [here](http://www.asp.net/whitepapers/aspnet4/breaking-changes). – David Sherret Feb 08 '16 at 18:24
  • It seems this has gone to 4.0, didn't work when it was 3.5! – Kris Feb 11 '16 at 17:23
6
<body>
     <form id="form1" runat="server">
          <div>
               <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="tx" DataValueField="vl">
               </asp:CheckBoxList>
          </div>
          <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /> 
     </form>
</body>
<script type="text/javascript">

function Button1_onclick() 
{
var itemarr = document.getElementById("CheckBoxList1").getElementsByTagName("span");
var itemlen = itemarr.length;
     for(i = 0; i <itemlen;i++)
     {
          alert(itemarr[i].getAttribute("dvalue"));
     }
return false;
}


</script>

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("tx");
        dt.Columns.Add("vl");
        DataRow dr = dt.NewRow();
        dr[0] = "asdas";
        dr[1] = "1";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "456456";
        dr[1] = "2";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "yjryut";
        dr[1] = "3";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "yjrfdgdfgyut";
        dr[1] = "3";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "34534";
        dr[1] = "3";
        dt.Rows.Add(dr);
        CheckBoxList1.DataSource = dt;
        CheckBoxList1.DataBind();
        foreach (ListItem li in CheckBoxList1.Items)
        {
            li.Attributes.Add("dvalue", li.Value);
        }
    }
}
stealthyninja
  • 10,343
  • 11
  • 51
  • 59
Swapna
  • 61
  • 1
  • 2
2

Had to do something really nasty in order to get this to work..

        <asp:Repeater ID="rptItems" runat="server">
            <ItemTemplate>
                <input ID="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("your_data_value") %>' />
                <label ID="iptLabel" runat="server"><%# Eval("your_data_field") %></label>
                <br />
            </ItemTemplate>
        </asp:Repeater>

Codebehind:

Private Sub rptItems_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptItems.ItemDataBound
    Dim checkBox As HtmlInputCheckBox = DirectCast(e.Item.FindControl("iptCheckBox"), HtmlInputCheckBox)
    Dim label As HtmlControl = DirectCast(e.Item.FindControl("iptLabel"), HtmlControl)

    label.Attributes.Add("for", checkBox.ClientID)
End Sub
danyim
  • 1,274
  • 10
  • 27
2

Stored in ViewState, you cannot access them on the client without some hacking.

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
2

To avoid hacking the checkbox list just use a repeater as such:

<asp:Repeater ID="rptItems" runat="server" DataSourceID="odsDataSource">
<ItemTemplate>
<input id="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("Key") %>'><%# Eval("Value") %></input>
</ItemTemplate>
</asp:Repeater>
rjarmstrong
  • 1,221
  • 12
  • 22
0

Removing <pages controlRenderingCompatibilityVersion="3.5"> caused an issue in some old code I was working on. I was getting this error. Once I got that error I realized it was too risky of a change.

To fix this, I ended up extending CheckBoxList and overriding the Render method to add an additional attribute containing the value to each list item:

public class CheckBoxListExt : CheckBoxList
{
    protected override void Render(HtmlTextWriter writer)
    {
        foreach (ListItem item in this.Items)
        {
            item.Attributes.Add("data-value", item.Value);
        }

        base.Render(writer);
    }
}

This will render the data-value attribute on the outer span tag.

Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
0

Swapna, Your answer absolutely works. So in order to check if the check box in the ASP.Net Checkboxlist is checked and then accumulate the list as a comma-delimited string, you can do as

C# Code-behind

ChkboxList1.DataSource = dsData;
ChkboxList1.DataTextField = "your-display-column-name";
ChkboxList1.DataValueField = "your-identifier-column-name";
ChkboxList1.DataBind();

foreach (ListItem li in ChkboxList1.Items)
{
    li.Attributes.Add("DataValue", li.Value); 
}

Then in Javascript do

var selValues = "";
var ChkboxList1Ctl = document.getElementById("ChkboxList1");
var ChkboxList1Arr = null;
var ChkboxList1Attr= null;

if (ChkboxList1Ctl != null)
{
   ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName("INPUT");
   ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName("span");
}
if (ChkboxList1Arr != null)
{
    for (var i = 0; i < ChkboxList1Arr.length; i++)
    {
       if (ChkboxList1Arr[i].checked)
           selValues += ChkboxList1Attr[i].getAttribute("DataValue") + ",";
    }
    if (selValues.length > 0)
       selValues = selValues.substr(0, selValues.length - 1);
}
akjoshi
  • 15,374
  • 13
  • 103
  • 121
user428602
  • 47
  • 2
  • 11
0
Easy Way I Do It.

//First create query directly From Database that contains hidden field code format (i do it in stored procedure)

SELECT Id,Name + '<input id="hf_Id" name="hf_Id" value="'+convert(nvarchar(100),Id)+'" type="hidden">' as Name FROM User

//Then bind checkbox list as normally(i bind it from dataview).

cbl.DataSource = dv;
cbl.DataTextField = "Name";
cbl.DataValueField = "Id";
cbl.DataBind();

//Then finally it represent code as follow.

<table id="cbl_Position" border="0">
<tbody>
<tr>
<td>
<input id="cbl_0" name="cbl$0" type="checkbox">
<label for="cbl_0">
ABC
<input id="hf_Id" name="hf_Id" value="1" type="hidden">
</label>
</td>
</tr>
</table>

This way you can get DataValueField as inside hiddenfield and also can get it value from client side using javascript.
Jigs17
  • 49
  • 4
0

I tried the following and its working for me:

<asp:CheckBoxList ID="chkAttachments" runat="server"></asp:CheckBoxList>

Server side binding:

private void LoadCheckBoxData()
        {

            var docList = new List<Documents>(); // need to get the list data from database
                    chkAttachments.Items.Clear();

                    ListItem item = new ListItem();
                  
                    foreach (var doc in docList )
                    {
                        item = new ListItem();
                        item.Value = doc.Id.ToString();
                        item.Text = doc.doc_name;
                        chkAttachments.Items.Add(item);
                    }
                }
    
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37