user426795
user426795

Reputation: 11663

Catching multiple values using JS

 <span>
    <label class="label">Color</label>
    <span class="foo"><input name="Color" value="Blue" class="customs" maxlength="100" type="text"/></span>
    </span>
 </span>

 <span>
     <label class="label">Brand</label>
      <span class="input-large"><input name="Brand" value="xxx" class="customs" maxlength="100" type="text"/></span>
    </span>
 </span>

I want all the input value using JS. I wrote

$('.customs').each(function() {

    alert($('.customs').val());

});

But Every times it gives me the first input value.

Required Alert output: Blue, Brand
Output comes: Blue, Blue 

Upvotes: 1

Views: 60

Answers (4)

JohnP
JohnP

Reputation: 50019

Since you're using a class as a selector, you're getting a collection. You can do something with it by putting it an array or iterating over it.

$('.customs').each(function() {
   alert($(this).val());//use this to refer to the current object
});

Upvotes: 0

Geoff
Geoff

Reputation: 9340

double check value vs. name in your two input definitions

Upvotes: 0

Sean Kinsey
Sean Kinsey

Reputation: 38046

You are evaluating the selector on each iteration, and I guess that when val is called on an array, it selects the first value.

Use

$('.customs').each(function() {
    alert($(this).val());
});

Or even better,

$('.customs').each(function() {
    alert(this.value);
});

as there is no need for the layer provided by val here.

Upvotes: 0

Tim
Tim

Reputation: 779

replace

alert($('.customs').val());

with

alert($(this).val());

Upvotes: 1

Related Questions