add click event to dynamically created checkboxlist(s)

I have a form that creates checkboxlists dynamically

Can I add a click even on each "node" so that it updates a hidden control with...
hdnFld.Value =s hdnFld.Value + id + ","

I want to do this on each check or uncheck
Either with the  rblMultiList or  rblMultiList.Item is fine

And I want to do this server side if at all possible

I cannot get my client side loop to work and am frustrated in the extreme

  Dim rblMultiList As New CheckBoxList
                            'dropdownlist.Width = 200		
                            rblMultiList.Style.Add("Width", "70%")
                            rblMultiList.RepeatDirection = RepeatDirection.Horizontal
                            ' rblMultiList.CellPadding = 2		
                            'rblMultiList.CellSpacing = 2		
                            rblMultiList.AutoPostBack = False
                            rblMultiList.ID = "rblMultiList" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID")
                            rblMultiList.CssClass = "chks chkquestions_" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID")
                            Dim selected As String = ""
                            Dim sss As String = ""
                            Dim dtview As New DataView(dS.Tables(1))
                            dtview.RowFilter = "PromotionSurveyQuestionID=" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID").ToString()
                            If dtview.Count > 3 Then
                                rblMultiList.RepeatColumns = 2
                            Else
                                rblMultiList.RepeatColumns = 3
                            End If
                            If dtview.Count > 0 Then
                                Dim dttemp = New DataTable()
                                dttemp = dtview.ToTable()
                                For n As Int32 = 0 To dttemp.Rows.Count - 1
                                    rblMultiList.Items.Add(New ListItem(dttemp.Rows(n)("AnswerText").ToString(), dttemp.Rows(n)("PromotionSurveyAnswerID").ToString()))
                                    If Not dttemp.Rows(n)("isSelected") = Nothing AndAlso dttemp.Rows(n)("isSelected") = "Yes" Then
                                        rblMultiList.Items(n).Selected = True
                                        Dim o As Object() = {IndividualID.ToString(), "ctl00_ContentPlaceHolder1_" + rblMultiList.ID, dS.Tables(0).Rows(j)("PromotionSurveyQuestionID").ToString(), dttemp.Rows(n)("PromotionSurveyAnswerID").ToString(), 1}
                                        dtSurveyControls.Rows.Add(o)
                                        Dim oo As Object() = {IndividualID.ToString(), PromotionLeadFormID.ToString(), dS.Tables(0).Rows(j)("PromotionSurveyQuestionID").ToString(), dttemp.Rows(n)("PromotionSurveyAnswerID").ToString(), 1}
                                        dtSurvey.Rows.Add(oo)
                                    End If
                                Next
                            End If
                            tdlbl.Controls.Add(lbl)
                            td.Controls.Add(rblMultiList)
                            tr.Cells.Add(tdlbl)
                            td.Style.Add("padding-left", "8px")
                            tr.Cells.Add(td)

Open in new window

Larry Bristersr. DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
To add a click event to a dynamically created checkbox use the on() function

Example
HTML
<ul class="chks"></ul>
<button class="check btn btn-primary">Go</button>
<pre id="result"></pre>

Open in new window

jQuery
<script>
var id = 0;
$(function() {
  $('.check').click(function() {
    id++;
	var label = $('<span>').html(' Checkbox [id: ' + id + ']');
	var cb = $('<input>', {type: 'checkbox', id: 'id' + id}).val(id);
	var li = $('<li>').append(cb).append(label);
	
	$('.chks').append(li);
  });
  $('.chks').on('click', ':checkbox', function() {
	$('#result').append('clicked: ' + this.value + "\n");
  });
});
</script>

Open in new window

Working sample here
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Larry Bristersr. DeveloperAuthor Commented:
Julian,
 This is a checkbox list
0
Julian HansenCommented:
The server side nature of the list is not important - it is what it looks like on the client that counts when you are dealing with JavaScript

The only code in the sample that is relevant to what you want to do is this
$('.chks').on('click', ':checkbox', function() {
	$('#result').append('clicked: ' + this.value + "\n");
  });

Open in new window

The rest of the code is just a sample container to demonstrate the functionality
What this code is doing is the .on() handler to bind to the container of whatever contains your checkboxes and when a click event happens checks to see if the target was a checkbox - if it is then it executes the handler code.

Again the handler code is irrelevant and there just for sample purposes - you wanted to know how to add a click event to a dynamically added checkbox - the above code does exactly that - how the checkbox was rendered (VB, C#, Java, PHP) does not matter.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Larry Bristersr. DeveloperAuthor Commented:
Julian,

My RadioButtonList portion works fine
--Script...RadioButtonList
                var surveydata="";		
                $('.rblsurvey').each(function () {		
                    debugger;		
                    var checked_radio = $("[id*="+$(this).context.id+"] input:checked");		
                    var value = checked_radio.val();		
                    var question = $(this).context.className.replace("rblsurvey rblMultiList_","");		
                    surveydata=surveydata+question+","+value+"|";		
                    //alert(surveydata);		
                    $("#ctl00_ContentPlaceHolder1_hdnsurveyvalues").val(surveydata);		
                });

Open in new window


  The checkboxlist(s) are built server side using the code below.
What I need is the loop to grab the QuestionID, AnswerID, "|"  if the checkbox(s) are checked.  

That is all I need to do and I am just brain locking on this

Dim rblMultiList As New CheckBoxList
rblMultiList.Style.Add("Width", "70%")
rblMultiList.RepeatDirection = RepeatDirection.Horizontal
rblMultiList.AutoPostBack = False
rblMultiList.ID = "rblMultiList" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID")
rblMultiList.CssClass = "chks chkquestions_" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID")
Dim selected As String = ""
Dim dtview As New DataView(dS.Tables(1))
dtview.RowFilter = "PromotionSurveyQuestionID=" & dS.Tables(0).Rows(j)("PromotionSurveyQuestionID").ToString()
If dtview.Count > 3 Then
    rblMultiList.RepeatColumns = 2
Else
    rblMultiList.RepeatColumns = 3
End If
If dtview.Count > 0 Then
    Dim dttemp = New DataTable()
    dttemp = dtview.ToTable()
    For n As Int32 = 0 To dttemp.Rows.Count - 1
        rblMultiList.Items.Add(New ListItem(dttemp.Rows(n)("AnswerText").ToString(), dttemp.Rows(n)("PromotionSurveyAnswerID").ToString()))
    Next
End If
tdlbl.Controls.Add(lbl)
td.Controls.Add(rblMultiList)
tr.Cells.Add(tdlbl)
td.Style.Add("padding-left", "8px")
tr.Cells.Add(td)

Open in new window

0
Julian HansenCommented:
You are focusing on server side code instead of client side code. When that code runs it generates HTML. The javascript that you add to the page needs to act on the generated HTML - the server code is not in play.

Let's do it this way. Run your page and then do a view source. Paste the HTML here.
0
Larry Bristersr. DeveloperAuthor Commented:
The page view source html is below
I have a asp.net Button with thiOnClientClick="SaveValidation();

Here is my current JavaScript
       <script>
            function SaveValidation() {
                var surveydata="";		
                $('.rblsurvey').each(function () {		
                    debugger;		
                    var checked_radio = $("[id*="+$(this).context.id+"] input:checked");		
                    var value = checked_radio.val();		
                    var question = $(this).context.className.replace("rblsurvey rblMultiList_","");		
                    surveydata=surveydata+question+","+value+"|";		
                    //alert(surveydata);		
                    $("#ctl00_ContentPlaceHolder1_hdnsurveyvalues").val(surveydata);		
                });

                $(".chks").each(function (index) {

                    var questionid = $(this).attr("class").replace("chks chkquestions_", "");
                    var answerid = "";

                    $(this).find(":checked").each(function (index) {
                        answerid = answerid + $(this).val() + ",";
                    });
                    //  alert(questionid + " |" + answerid)                                        
                    $("#hdnsurveyvaluesChk").val($("#hdnsurveyvaluesChk").val() + questionid + "|" + answerid + ";");
                });

                debugger;
                if (document.getElementById("ctl00_ContentPlaceHolder1_strFirstName").value == "") {
                    document.getElementById("ctl00_ContentPlaceHolder1_diverror").style.display = "block";
                    return false;
                }
              
                javascript: __doPostBack('ctl00$ContentPlaceHolder1$btnAdd', '');
                document.getElementById("ctl00_ContentPlaceHolder1_divsuccess").style.display = "block";
            }
        </script>

Open in new window

HTML CODE
<table id="ctl00_ContentPlaceHolder1_rblMultiList22" class="chks chkquestions_22" border="0" style="Width:70%;">
    <tbody>
        <tr>
            <td><input id="ctl00_ContentPlaceHolder1_rblMultiList22_0" type="checkbox" name="ctl00$ContentPlaceHolder1$rblMultiList22$0" /><label for="ctl00_ContentPlaceHolder1_rblMultiList22_0">Cabin</label></td>
            <td><input id="ctl00_ContentPlaceHolder1_rblMultiList22_1" type="checkbox" name="ctl00$ContentPlaceHolder1$rblMultiList22$1" /><label for="ctl00_ContentPlaceHolder1_rblMultiList22_1">Hotel Room</label></td>
            <td><input id="ctl00_ContentPlaceHolder1_rblMultiList22_2" type="checkbox" name="ctl00$ContentPlaceHolder1$rblMultiList22$2" /><label for="ctl00_ContentPlaceHolder1_rblMultiList22_2">Suite</label></td>
        </tr>
    </tbody>
</table>

Open in new window

0
Larry Bristersr. DeveloperAuthor Commented:
I didn't notice that you had not added on the Contentplaceholder to the front of #result

This works
0
Julian HansenCommented:
Glad you found a solution.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.