Piscean
Piscean

Reputation: 3079

Why am i getting always undefined checkbox value?

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.

Upvotes: 0

Views: 899

Answers (1)

Samich
Samich

Reputation: 30115

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>');

Upvotes: 3

Related Questions