user11119835
user11119835

Reputation: 23

Populate an object and post it through jquery ajax

In my jsp page i have some input tags with id of 'opt'. I need to get the value of all of them and create the following list:

Votes= {
vote={opt:'one'}, vote={opt:'two'}, vote={opt:'three'},...
}

How can i do it? I have written the following code to get the value those inputs and store them in an array but it only gets the first of them:

Var opts=[] , ids;
$("#myform").each(function(){
ids=$("#opt").val();
opts.push(ids);
});

Upvotes: 1

Views: 39

Answers (2)

Adophilus
Adophilus

Reputation: 310

Here try this

...
var votes = new Array(); // the array to hold the votes
document.querySelectorAll("#opt").forEach(function (elem) {
    votes.push(elem.value);
});

$.ajax({
...
"data": votes,
...
});

I hope this helps

Upvotes: 1

user11119835
user11119835

Reputation: 23

In order to send through ajax without problem it is enough to modify line 3 of the answer as below:

Votes.push({'Opt':elem.value});

Now votes will be a list of vote objects and not just an array of strings. Therefore ajax will work properly

Upvotes: 0

Related Questions