0

I have a set of textboxes which I want to iterate in order to get a list of their values. So I used the following appraoch:

var locations = [];
$("input[type=text]").each(i => {
    var obj = $(this);
    locations.push(obj.value)
});

When I debug that, obj is the main-window, not the current element within my DOM. Thus obj.value just returns undefined.

However when I just use $("input[type=text]").val() only the very first value is returned.

3
  • 1
    Read about this in arrow functions developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 30, 2020 at 14:46
  • 1
    You can change your all input names like this; locations[]. When you fetch them on backend all will come in an array. Commented Nov 30, 2020 at 14:46
  • @j08691 Wow, that was simple. Thanks for the hint. Feel free to get an easy accept... Commented Nov 30, 2020 at 14:48

3 Answers 3

1

You can use snippet in below. map function gets all input values one by one with the function in it.

$("#print").on("click",function(){
  var values = $("input[name='location[]']")
              .map(function(){return $(this).val();}).get()
              
  console.log(values);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='location[]'>
<input type='text' name='location[]'>
<input type='text' name='location[]'>
<input type='text' name='location[]'>

<a href='#' id='print'>print</a>

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I like the map-call. That´s exactly what I was looking for.
0

Maybe this is help you,

var locations = [];
$("input[type=text]").each(function(i){
  var aaa = $(this).val();
  locations.push(aaa);
});

Comments

0

As of the docs an arrow-function "does not have its own binding for this". So we replace the arrow-function by a classic function-expression:

$("input[type=text]").each(function(i) {
    var obj = $(this);
    locations.push(obj.value)
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.