1

I have a group 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?

2
  • $('.playerSport').val() these will return you only one value and not an array then how can you do .join ??? Commented Apr 19, 2011 at 15:21
  • This is probably not the main problem, but you are missing closing brackets on $('input[name="playerSport"') it should be $('input[name="playerSport"]') that is on the 1st line and the 7th line Commented Apr 19, 2011 at 15:24

3 Answers 3

1
var a = $.map($(".playerSport,.playerPosition,.playerNumber"), function(el) {
 return $(el).val();
});
// now 'a' is an array containing the values.
Sign up to request clarification or add additional context in comments.

2 Comments

ah! I HAVE to do the return. Cool, that did it. I'll select this as the answer once the time runs out. thanks!
could do the same thing also as $("...").map(function (el) {...}
1

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

1 Comment

You are abusing the .val function. Use .map for this. .val is intended to set the value for each element to the return value of the function.
0

.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.