0

I need to create a variable to use with in the ajax data property. The out put needs to look like this:

data: { brand: 1, brand: 4 }

I have a few checkboxes, depending on what the user clicks I would like the list to change.. currently I have this:

$('body').on('change','form[name=checkboxes] input',function(){

var result = [];
$.each( $('form[name=checkboxes]').serializeArray(), function() {
    result.push({
        name: this.name,
        value: this.value
    });
});

console.log(result);

$.ajax({
    type: "POST",
    url: "/echo/html/",
    data: { brand: 1, brand: 4 }
}).done(function( data ) {

});

});

But result outputs objects.

image of the result I created

Does anyone have any suggestions, am I on the right track?

I've created a JS fiddle to help http://jsfiddle.net/samstimpson/hzy9jxve/

Edit

My goal is to build this "data: { brand: 1, brand: 4 }" dynamically. If the user clicks a load of checkboxes I ultimately want to pass a list in to the ajax data value.. what Ive done above may not be correct, Im looking for a way of doing this.

1
  • You can't have an object that contains the same key name; {brand: 1, brand: 4} won't work. Commented Nov 26, 2014 at 22:45

2 Answers 2

2

you required json is illegal because the brand field is repeated twice(??)

i created a fix in jsFiddle for you: http://jsfiddle.net/ymzrocks/hzy9jxve/1/

var result = {}, i = 1;
$.each( $('form[name=checkboxes]').serializeArray(), function() 
{
    result[this.name + i] =  this.value ; i++;
});

it basically turns the brand fields to brand1, brand2, ... etc

i really think that you should use an array or rephrased your question

Sign up to request clarification or add additional context in comments.

3 Comments

ok, thats cool. My goal is to pass the checkbox name and value through to a page via a POST.
great :) i still think that a single array with all the values selected (per group) will be better... { brand : [2, 4, 1], other_brand: [2, 3] }
If you think its better I'll look in to it! One thing though would that format be valid passing in tot he ajax data field?
1

I imagine you would use JSON.stringify function

http://msdn.microsoft.com/en-us/library/ie/cc836459(v=vs.94).aspx

the following post might also be a good read

http://geekswithblogs.net/rgupta/archive/2014/06/25/combining-jquery-form-serialize-and-json.stringify-when-doing-ajax-post.aspx

Comments

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.