Anderson
Anderson

Reputation: 1200

How to iterate all elements based on name attribute and modify the value in Jquery?

Below is my HTML snippet,

<div class="direct-service hide">
    ..   
    <input handle="input" type="hidden" name="./season" value="spring">
    <input handle="input" type="hidden" name="./season" value="">
    ...
</div>

I want to iterate all element inside direct-service class and look for ./season name attribute and check if the value is empty. If it is empty I need to modify the element as

<input handle="input" type="hidden" name="./season@Empty" value="">

I tried to get the value based name property with below code

$("input[name='./season']").val();

But it is giving me the value for first element and not giving me the second element. Seemed like I need to scan all element inside the div class. Could you anyone tell me the best way to manage this case?

Upvotes: 0

Views: 869

Answers (2)

oussama zaqouri
oussama zaqouri

Reputation: 324

You can use .eq() function, example:

$("input[name='./season']").eq(0).val(); // Get first element
$("input[name='./season']").eq(1).val(); // Get second element

Upvotes: 1

Barmar
Barmar

Reputation: 781096

Use .map() to iterate and return an array of all the values.

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

Or if you want to do something to each of them, use .each()

$("input[name='./season']").each(function() {
    if (this.value == "") {
        $(this).setAttr("value", "");
    }
}).get();

Upvotes: 5

Related Questions