Each time you have an instance of your UserControl, you also re-add the javascript function. You have to add the javascript function once, so remove it from UserControl and add it to the .aspx main page and change it to something like this:
function CheckItem(chk, txt, hid) { var tbl = chk.parentNode.parentNode.parentNode; //table with checkboxes var options = tbl.getElementsByTagName('input'); //checkboxes var arrItems = new Array(); //array for selected items for (i = 0; i < options.length; i++) { var opt = options[i]; if (opt.checked) { arrItems.push(opt.value); //if checked, push it in array } } txt.value = arrItems.join(", "); //use join to comma separate them hid.value = arrItems.join(); //comma separated without extra space }
Now let me call the function from each flag, not from the CheckBoxList. To do this, we add an attribute each time the user clicks on the checkbox element, and not the entire control, placing it in the code behind:
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { foreach (ListItem li in this.chkList.Items) { li.Attributes.Add("onclick", "CheckItem(this, document.getElementById('" + txtCombo.ClientID + "'), document.getElementById('" + hidVal.ClientID + "'))"); } } }
Finally, remove any javascript events from your CheckBoxList, as we did this in the code behind:
<asp:CheckBoxList ID="chkList" runat="server" Height="80"> <asp:ListItem Text="Contains" Value="Contains" /> <asp:ListItem Text="Related" Value="Related" /> <asp:ListItem Text="Exact" Value="Exact" /> </asp:CheckBoxList>
source share