I have a form with 4 different checkboxes with ids namely filter_AFFILIATION_1, filter_AFFILIATION_2 and so on till 4. I am trying to send the checked checkboxes values to the server dynamically by using an ajax call. Here is my code:
$('input[type="checkbox"]').change(function(){
var ids = ['filter_AFFILIATION_1','filter_AFFILIATION_2','filter_AFFILIATION_3','filter_AFFILIATION_4'];
for(var i = 0; i < ids.length; i++){
if(document.getElementById(ids[i]).checked === true){
var data = {};
data['request'+i] = $('#'+ ids[i]).val();
console.log(data);
}
}
$.ajax({
type: 'POST',
url: Routing.generate('listingpage'),
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function(result,status,xhr){
console.log(result);
}
If you look at
data['request'+i] = $('#'+ ids[i]).val();
console.log(data);
part of the code, the output of console.log if I click
-
Only first checkbox:
{request0: "1"}
-
First and then second checkbox:
{request0: "1"}
{request1: "2"}
-
First and then second and then 3rd checkbox:
{request0: "1"}
{request1: "2"}
{request2: "3"}
-
First then second, then third and then uncheck second checkbox:
{request0: "1"}
{request2: "3"}
Now my problem is that I want to send the data as a single object rather than multiple objects such as if the user clicks first checkbox and then second the output of console.log(data) should be
`{request0: "1", request1: "2"}`
I've tried a lot of different methods but nothing seem to work. Any ideas?
Aucun commentaire:
Enregistrer un commentaire