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

Time:11-24

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?

CodePudding user response:

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();

CodePudding user response:

You can use .eq() function, example:

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