0

I have an HTML form with multiple selects that all have the same class. Out of these only one appears at a time depending on previous selections and thus only one of them can have a value at a time.

What is the proper / best way to get the value of all these selects put together ?

They look like this:

<select class="formField" id="input1"> ... list of options ... </select>
<select class="formField" id="input2"> ... list of options ... </select>
<select class="formField" id="input3"> ... list of options ... </select>

Would the following be correct in this case ?

$('.formField').val();

Thanks for any help with this, Tim.

2 Answers 2

4

You have to use .each() to iterate through those elements and add their value in a separate variable.

Try this,

var xSum = 0;

$('.formField').each(function(){
  xSum += parseInt($(this).val());
 })

alert(xSum);

For your reference read this : .each()

Update

The following code will concatenate the values.

var xResultString = '';

$('.formField').each(function(){
  xResultString += $.trim($(this).val());
 })

alert(xResultString);

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

Man you were quick! Good job.
Thanks ! The values of my select options only contain text. I guess I would not need parseInt then, right ? How would I do it then ?
@user2571510 so you want to concatenate it right.? I misunderstood with that word sum.
Thats perfect - exactly what I was looking for ! Sorry for the misleading description.
2

You need a iterate through all of them. This script will concatenate all the strings.

var selectValues = "";

$('.formField').each(function () {
  selectValues += $(this).val();
});

console.log(selectValues);

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.