views:

673

answers:

2

Setting onchange event for CheckBoxList using the following code doesn't work.

chkListUserGroup.Attributes.Add("onchange", "document.forms[0].isRecordModified.value='true';");

How to set onchange event for CheckBoxList?

+1  A: 

Use onclick event,

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CheckBoxList1.Items.Add("A");
            CheckBoxList1.Items.Add("B");
            CheckBoxList1.Items.Add("C");
            CheckBoxList1.Items.Add("D");

            foreach (ListItem item in CheckBoxList1.Items)
            {
                CheckBoxList1.Attributes.Add("onclick", "document.forms[0].isRecordModified.value=document.activeElement.checked");    
            }
        }
    }
adatapost
This is the only way I have managed to catch the event for check box lists
Adam Fox
A: 

Well actually it should be working. Because I write something in my code and it worked. It seems you need to check your javascript code by simply changing it with alert('hello');

 foreach (ListItem item in CheckBoxList1.Items)
 {
    item.Attributes.Add("onchange", "alert('hello')");
 }

This is my simple code and it is working.

Braveyard
It works properly for CheckBox.
Ahmed
@Aaron: I just deleted my answer, as you are absolutely right. Didn't know that the onchange event would automatically propagate to child elements.
Jørn Schou-Rode
How to set it for an item in CheckBoxList. onchange event is attached to label element not to input label itself.
Ahmed
@Ahmed, Okay I've changed the code.
Braveyard
The same issue, it affects label not input element.this is how it's rendered ...<SPAN onchange="document.forms[0].isRecordModified.value='true';"><INPUT id=chkListUserGroup_2 tabIndex=6 onclick="javascript:setTimeout('__doPostBack(\'chkListUserGroup$2\',\'\')', 0)" type=checkbox name=chkListUserGroup$2><LABEL for=chkListUserGroup_2>ACCOUNTS USER GROUP</LABEL></SPAN>
Ahmed