Reputation: 49
js length doesnt show correct length of element and find() cant get value of an elements i have code like this:
<div id="mobiles">
<input name="mobiles[]" id="mobiles0">
<input name="mobiles[]" id="mobiles1">
<input name="mobiles[]" id="mobiles2">
.
.
.
</div>
inputs with id mobiles1 and more are dynamically created by appending elements. i want to get number of inputs i used 2 way
$('#mobiles').children('input').length;
// it return nothingdocument.getElementsByName('mobiles[]').length;
// it returns incorrect value for example 8 for 3 input or 16 for 4 input or 32 for 5 input elements. it seems like powers of 2second problem is i cant get value of third input and after that. i just get value of first and second input with below code.
var xlen = document.getElementsByName('mobiles[]').length;
for (i = 0; i < xlen; i++) {
var data = $('div').find('#mobiles' + i).val();
alert(data);
}
or using $('#mobiles'+i).val();
return nothing.
Upvotes: 0
Views: 2107
Reputation: 17190
Using $("#mobiles input").length
should also work, check next example:
function getValues()
{
var xlen = $("#mobiles input").length;
for (i = 0; i < xlen; i++)
{
var data = $("#mobiles #mobiles" + i).val();
console.log(data);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mobiles">
<input name="mobiles[]" id="mobiles0">
<input name="mobiles[]" id="mobiles1">
<input name="mobiles[]" id="mobiles2">
</div>
<button onclick="getValues()">Get Values</button>
Upvotes: 0
Reputation: 93
Getting the length:
$("#mobiles").find("input").length
Getting value of third element in the array
$("#mobiles").find("input")[2].value
There are others ways of course, but this works for sure.
Upvotes: 1
Reputation: 15847
It's generally not recommended to combine vanilla js with jQuery.
to loop through inputs use pure jQuery.
$("#mobiles input").each(function(){
console.log($(this).val());
});
edited to remove size recommendation
Upvotes: 1