Reputation: 37113
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.
Upvotes: 0
Views: 25
Reputation: 37113
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)
});
Upvotes: 0
Reputation: 73
Maybe this is help you,
var locations = [];
$("input[type=text]").each(function(i){
var aaa = $(this).val();
locations.push(aaa);
});
Upvotes: 0
Reputation: 1572
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>
Upvotes: 1