keshav
keshav

Reputation: 876

'undefined' elements in the array

I have the following JavaScript I am using to save selected check boxes:

function SubmitCheckBoxes()
{
    alert("test");
    var selectedIDs = [];
    var x = 0;
    a = document.getElementsByTagName("input");
    for (i = 0; i < a.length; i++) {

        if (a[i].type == "checkbox" ) {
            if (a[i].checked) {
                alert(a[i].value);
                selectedIDs[x] = a[i].value;
                x++;
            }
        }
    }
    $.post('./Courses/SaveAndRedirect', selectedIDs, function (data) { });
}

However when I look at the form data being submitted all its says is undefined: undefined for each element in the array.

Not sure what the problem is here.

Upvotes: 0

Views: 122

Answers (3)

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

You can try something like this:

var selectedIDs = [];
$('input[type="checkbox"]:checked').forEach(function(i, e){
   selectedIDs.push($(e).val());
});
$.post('./Courses/SaveAndRedirect', selectedIDs, function (data) { });

Upvotes: 0

einstein
einstein

Reputation: 13850

It is the data attribute in the jquery post method that is wrong. It can't take an array as a parameter. Here is the documentation

data map or string that is sent to the server with the request.

Try using a object literal instead:

$.post('./Courses/SaveAndRedirect', {selectedIDs: selectedIDs}, function (data) { });

I would also try writing selectedIDs[x] = a[i].value; differently:

selectedIDs.push(a[i].value);

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

I think the problem may be that your post variables are associated with just a numeric instance rather than a field name

Upvotes: 0

Related Questions