开发者

How do I get an array from inputs in JQUERY?

I have a group开发者_StackOverflow中文版 of inputs to get player info:

<select name="playerSport" class="playerSport">...</select>
<input type="text" name="playerPosition" class="playerPosition" />
<input type="text" name="playerNumber" class="playerNumber" />
<button id="submit">Submit</submit>

There can be n number of each field. I'm using AJAX with this form so I want to pull each field into an array. Have an array for each sport, position, and number.

i've reviewed the examples from these pages: jquery.val() and jquery.map()

i've tried:

var sport = $('input[name="playerSport"').val() || [];
var sportList = sport.join(",");

var sport = $('.playerSport').val() || [];
var sportList = sport.join(",");

$('input[name="playerSport"').map().get().join(",");

$('.playerSport').map().get().join(",");

these return blank results. Odds are I'm missing something fairly obvious. Any ideas?


var a = $.map($(".playerSport,.playerPosition,.playerNumber"), function(el) {
 return $(el).val();
});
// now 'a' is an array containing the values.


Another option is to pass a function into .val()

var values = [];
$(":input").val(function(index, value){
    values.push(value);
});

Also you can use :input if you want to select all <select/>, <input type="text"/>, and <textarea/> elements.

Code example on jsfiddle


.val() will return an array for an element with multiple values (like a multi-<select>), but it does not return an array of values from each element in the selected node set.

You'll need to build up an array in a callback function, possibly using $.map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜