Identify the selected INPUT array key

Asked

Viewed 58 times

0

In an HTML form I created a field input[type='text'] with the attribute name='input[][nome]' and this field is created in the DOM dynamically on demand of the user, if the user create 3 new inputs the return of the attribute name in the console.log would be:

input[0][name]

input[1][name]

input[2][name]

I’m using Jquery to facilitate development time and a good part is in Javascript, I made a debugger that displays in console.log which input is receiving the focus and with the code below returns me the attribute name.

<input type='text' name='input[][nome]' class='add-item'/>

<script>
$('.add-item).on('click',function(){
    var nomeInput = $(this).attr('name');
    console.log(nomeInput); // retorna input[0][nome]
})
</script>

Inside the javascript code I would like to check what is the value of the current key, in the above case it is 0, but it is possible to identify this without structural change of this function, just incrementing the same?

1 answer

2


I think you are wrong. Your code does not return the index of the input within the brackets, it returns the value of the attribute as it is in the HTML. Behold:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='input[][nome]' class='add-item'/>

<script>
$('.add-item').on('click',function(){
    var nomeInput = $(this).attr('name');
    console.log(nomeInput); // retorna input[][nome]
})
</script>

Now, if you want to know what the content of the element within a collection with the same class, you can use the method .index():

$('.add-item').on('click',function(){
    var indice = $(this).index();
    console.log("Índice do input:", indice, ". Deveria ser:", indice-1); // retorna o índice do elemento
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='input[][nome]' class='add-item'/>
<input type='text' name='input[][nome]' class='add-item'/>
<input type='text' name='input[][nome]' class='add-item'/>

I don’t know why water loads in the snippet here the index returns an extra number: 1, 2 and 3. Test in a file . html in your browser that will return correctly: 0, 1 and 2.

In this JSFIDDLE works properly.

  • 1

    solved general, I had mapped everything to get the index, unknown . index(), today tested . map() and returned different, should report the divergence of the snippet to the OS. Thank you cordial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.