Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: pushing array of values in serializeArray

I have these:

<input class="orders" name="orders[]" value="1">
<input class="orders" name="orders[]" value="2">
<input class="orders" name="orders[]" value="3">

I try add values of orders to an serializeArray in JQUERY.

I do this:

var datastring = $("#form1").serializeArray();

var orders = [];
$('input.orders').each(function() {
       orders.push($(this).val()); 
 });
 datastring.push({name: "orders", value: orders});

in server side,(when I convert it into a json format) I want ["1","2","3"]

but now only I get a string:1,2,3

I try change it to:

datastring.push({name: "orders[]", value: orders});

Now when I convert it to json string (in server side) I get this:

["1,2,3"]

can please tell me my mistake?

like image 390
ANDA Avatar asked Oct 17 '25 18:10

ANDA


1 Answers

What you want is an array with objects that have the same name

var datastring = $("#form1").serializeArray();

$('input.orders').each(function() {
    datastring.push({name: this.name, value: this.value}); 
});

And make you sure you use the correct class, remove the brackets

<input class="orders" name="orders[]" value="1">
<input class="orders" name="orders[]" value="2">
<input class="orders" name="orders[]" value="3">

This will give you an array looking like

[
    {
        "name": "orders[]",
        "value": "1"
    },
    {
        "name": "orders[]",
        "value": "2"
    },
    {
        "name": "orders[]",
        "value": "3"
    }
]

jQuery will in turn parse that array to the string orders[]=1&orders[]=2&orders[]=3 when submitted, which is what most serverside languages that parse [] as form groups expect, both the key and the value for each element.

like image 110
adeneo Avatar answered Oct 20 '25 09:10

adeneo