0

I am creating some checkboxes in a div using these line of code:

 for(j=0;j<allActivities.length;j++){
   $('#activity_checkboxlist').append('<input type="checkbox" id="checkbox"'+j+' value="'+allActivities[j].activitynumber+'"/>'+allActivities[j].activityname+'<br>');
 }

Where activity_checkboxlist is a div. Now i am checking if a check box is checked then put its value in an array. I am doing that using this code:

var selectedareas = new Array();

for (i = 0; i < allActivities.length; i++) {

    var chkval = $('#checkbox' + i + ':checked').val();
    alert(chkval);
    if (chkval !== undefined) {
        selectedareas.push(chkval);
    }
}

That alert always shows that chkval's value is undefined. even i check those checkboxes. Is there any wrong with my code? Thanks in advance.

4
  • please post HTML... and also the JS that defines allActivities Commented Nov 28, 2011 at 10:03
  • 1
    BTW, not related to your question but it would be easier for you to fetch the checked values by doing $('#activity_checkboxlist :checkbox:checked').each(function(){});. Commented Nov 28, 2011 at 10:05
  • but then how i will add value of that specific checkbox in selectedareas array? Commented Nov 28, 2011 at 10:13
  • 1
    You can still use the codes inside the for-loop. Only difference is that you'll use var chkval = $(this).val() instead to get the checkbox's value, or selectedareas.push($(this).val());. Commented Nov 28, 2011 at 10:26

1 Answer 1

3

Have you checked you HTML after generatinng? You have put " in the worong part of the line.

With:

$('#activity_checkboxlist').append('<input type="checkbox" id="checkbox"'+j+' value="'+allActivities[j].activitynumber+'"/>'+allActivities[j].activityname+'<br>');

You have IDs like id="checkbox"1 value=.... Move your closing " to the second part to generate the right IDs:

$('#activity_checkboxlist').append('<input type="checkbox" id="checkbox'+j+'" value="'+allActivities[j].activitynumber+'"/>'+allActivities[j].activityname+'<br>');
Sign up to request clarification or add additional context in comments.

1 Comment

@JohnP Thanks for the english lesson :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.