Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items to an array and then serialize() javascript

I'm trying to add an item to an array in javascript and then serialize the array. However, it doesn't seem to be working.

Please see below code, what am I doing wrong?

var currentParent = $(this).closest('tr');
var items = $("input,select", currentParent);
items["_token"] = $('input[name=_token]').val();
var strData = items.serialize();
like image 585
V4n1ll4 Avatar asked Nov 10 '22 10:11

V4n1ll4


1 Answers

Method serialize needs to be applied to a whole form, not to specific items in array, if you want to serialize existing object or array you need to use param instead

http://api.jquery.com/jquery.param/

As an example :

<form action="">
   <input class="token" name="token" value="someValue" />
   <input class="someData" name="someData" />
</form>

<script>
    alert($('form').serialize()) // should show you someData=&token=someValue
</script>

https://jsfiddle.net/4cxa36vp/

... or ...

var options = {
    token : $('input.token').val(),
    someData : null
}

alert($.param(options)) // should give you the same

https://jsfiddle.net/0ec8axot/

Also, make sure that your form fields have attribute name

Serialize form not working in jQuery

like image 173
Anonymous Avatar answered Nov 15 '22 05:11

Anonymous