hsoft
hsoft

Reputation: 49

jquery find and length

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

  1. $('#mobiles').children('input').length; // it return nothing
  2. document.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 2

second 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

Answers (3)

Shidersz
Shidersz

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

aexposito
aexposito

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

imvain2
imvain2

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

Related Questions