0

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?

1
  • 1
    eachGsm isn't an array , on your each loop eachGsm contains your input type text value, if you want an array you have to create it and push the values inside Commented Dec 7, 2020 at 23:57

2 Answers 2

1

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);
    });
})
Sign up to request clarification or add additional context in comments.

Comments

0

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/

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.