Cara1
Cara1

Reputation: 3

Loop through array of input objects

Lets say I have these HTML objects:

<button id="addMore" class="button">+</button>

<div id="fieldList">
    <input type="text" name="gsm[]" placeholder="GSM" required>
    <input type="text" name="gsm[]" placeholder="GSM" required>
    <input type="text" name="gsm[]" placeholder="GSM" required>
</div>

Now I want to loop through each one of them in JavaScript. Each of the input text has different values. This is what I have tried (the current code is a small snippet of a bigger code):

$('input[name^="gsm"]').each(function(i,obj) {  
        var eachGsm = $(this).val();
        
        "This line has " + eachGsm[i] + ", as the value." + "%0D%0A" +
    });

When running this, the script gives me: [object Object]. What is the correct approach?

Upvotes: 0

Views: 416

Answers (2)

John Paul R
John Paul R

Reputation: 707

In this case, you can simply do

$('input[name^="gsm"]').each(function(i) {          
    console.log("This line has " + this.value + ", as the value." + "%0D%0A")
});

In the context of this function, this is the object referring to the HTML input element, and this.value is the text content entered by the user.

A runnable example: https://jsfiddle.net/23ao7mup/1/

Upvotes: 0

Nicholas Porter
Nicholas Porter

Reputation: 2951

You're already iterating over the list of elements, therefore this is already your desired value.

<button id="addMore" class="button">+</button>

<div id="fieldList">
    <input type="text" name="gsm[]" placeholder="GSM" value='1' required>
    <input type="text" name="gsm[]" placeholder="GSM"  value='2' required>
    <input type="text" name="gsm[]" placeholder="GSM" value='3' required>
</div>
$('document').ready(()=>{
  $('input[name^="gsm"]').each(function(i,obj) {  
        var eachGsm = $(this).val();
         console.log("each: " + eachGsm);
    });
})

Upvotes: 1

Related Questions