简体   繁体   中英

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();

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

Try the below javscript code snippet. I have not tried but i think it might work:

var currentParent = $(this).closest('tr');
var items = $(currentParent).find("input, select");
items["_token"] = $('input[name=_token]').val();
var strData = items.serialize();

See the below fiddle link: https://jsfiddle.net/nanncngr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM