0

I have a form containing a list of text fields

<input type="text" name="list[]" value="">
<input type="text" name="list[]" value="">

I'm running some custom jQuery to validate the input and do a few other things, before displaying a JSON chunk to the user. What I want to achieve is these elements should become a standard javascript array a la:

{"list":["something","something else"]}

Is there a simple call I can make on the specific element to pull it in as an array, something like this?

var jsonVars = {};
jsonVars['list'] = $("input[name=list]").getArray();
Ben Dauphinee
  • 4,061
  • 8
  • 40
  • 59
  • If you had an actual form you could do `$(form).serializeArray()` – adeneo Dec 16 '13 at 18:55
  • @adeneo I do have a form, but I don't want to grab the whole form contents. I'd have to iterate over the whole map to find the one target I'm looking for that way. – Ben Dauphinee Dec 16 '13 at 19:01
  • I believe you could do `$('[input[name^=list]').serializeArray()` but the format isn't what your plugin wants. You would need to run that `serializeArray()` through another loopie loop. – Bill Criswell Dec 16 '13 at 19:02

2 Answers2

1

With the structure you have and assuming you want to get the values you could do:

var jsonVars = {};
jsonVars['list'] = $('input[name="list[]"]').map(function(){return this.value;}).get();

You can use $('input[name="list[]"]').serializeArray() but will return in a different format as array of objects (with name and value).

PSL
  • 123,204
  • 21
  • 253
  • 243
0

There's jQuery's serialize function. This topic is similar to yours and might give you some more advanced insight.

Community
  • 1
  • 1
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83