0

Input fields occur dynamically by what the user needs in my script.

For example:

<div class='row'><input class='number' type='text' /><<input class='total' type='text' /></div> 
<div class='row'><input class='number' type='text' /><<input class='total' type='text' /></div> 
<div class='row'><input class='number' type='text' /><<input class='total' type='text' /></div> 

I want to know on keyup which input field is changed and do something with the inputted value. My idea is to do that by the class index.

I tried to get the class index by the following script:

$(document).ready(function(){
   $(".number").keydown(function(){
    alert($(this).index());
    });
});

But which field I test, he shows index 0 instead of index 1 or two if I type something in an other input field. What am I doing wrong?

1 Answer 1

2

Without arguments .index returns the index of the element among its siblings. The .number element always seems to be the first child of its parent, so the index is always 0.

You can either do:

$(this).parent().index();

if each of the siblings of the parent element contains a .number element.

Or select all .number elements first and get the index of the element within that set:

var $numbers = $('.number');
// ...
$numbers.index(this);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.