Reputation: 3246
Well, i'm using index()
to get the current index of a element and then using it with eq
and gt
selectors to enable and disable inputs.
but, i believe that index()
only work by searching the sibling elements. So, the way as my html structure are now, the index is not helping me. How can i make this work?
var $cascade = $(".cascade-discount-2"); // switch to 1
$("input", $cascade).on("keyup", function(){
var $this = $(this);
index = $this.index();
if($.isNumeric($this.val())){
$("input", $cascade).eq(index+1).attr("disabled", false);
}else{
$("input:gt("+index+")", $cascade).attr("disabled", true);
}
});
html structure that dos not work:
<div class='sep cascade-discount-1'>
<div class='bla'>
<input type="text" placeholder="0" />
</div>
<div class='bla'>
<input type="text" placeholder="0" disabled='disabled'/>
</div>
<div class='bla'>
<input type="text" placeholder="0" disabled='disabled'/>
</div>
here is a fiddle with a working and not working demo
Upvotes: 0
Views: 399
Reputation: 1141
Check the index of the parent element may help:
index = $this.parent().index();
Upvotes: 0
Reputation: 67187
The code written by you will suits for the second sort of DOM
structure, Because all of those input
elements are the siblings
each other. But in the first structure of DOM
you just wrapped all of those input
elements inside another div
. So that your code will return 0
always.
Try this,
var $cascade = $(".cascade-discount-1");
$("input", $cascade).on("keyup", function(){
var $this = $(this);
index = $(this).closest('div').index();
if($.isNumeric($this.val())){
$("input", $cascade).eq(index+1).attr("disabled", false);
}else{
$("input:gt("+index+")", $cascade).attr("disabled", true);
}
});
Upvotes: 2
Reputation: 388316
The no-argument variant of .index() will the index of the element with respect its siblings, in your case all input elements are the first child of its parent.
But there is a second variant which takes a argument
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
var $cascade = $(".cascade-discount-1"),
$inputs = $cascade.find('input'); // switch to 1
$inputs.on("keyup", function () {
var $this = $(this);
index = $inputs.index(this);
if ($.isNumeric($this.val())) {
$("input", $cascade).eq(index + 1).attr("disabled", false);
} else {
$("input:gt(" + index + ")", $cascade).attr("disabled", true);
}
});
Demo: Fiddle
Upvotes: 1