I have the following html:
<div> <input type="text" maxlength="2" class="day-spin-month"></input> <span>/</span> <input type="text" maxlength="2" class="day-spin-day"></input> <span>/</span> <input type="text" maxlength="4" class="day-spin-year"></input> </div>
I am attempting to change focus to the next input. I have it working the following 2 ways.
$('.day-spin-month').on('keyup', function () { if (this.value.length >= 2) { $(this).next().next().focus(); } }); $('.day-spin-day').on('keyup', function () { if (this.value.length >= 2) { $(this).next().next().focus(); } });
fiddle: http://jsfiddle.net/dan_vitch/JbQaN/1/
$('.day-spin-month').on('keyup', function () { if (this.value.length >= 2) { var test=$(this).next() var test2= $(test).next('input'); test2.focus(); } }); $('.day-spin-day').on('keyup', function () { if (this.value.length >= 2) { var test=$(this).next() var test2= $(test).next('input'); test2.focus(); } });
fiddle: http://jsfiddle.net/dan_vitch/JbQaN/2/
but it doesnt work this way:
$('.day-spin-month').on('keyup', function () { if (this.value.length >= 2) { $(this).next('input').focus(); } }); $('.day-spin-day').on('keyup', function () { if (this.value.length >= 2) { $(this).next('input').focus(); } });
fiddle: http://jsfiddle.net/dan_vitch/rJwyE/2/
I would like to use the way that is not working. I am not sure if its my selector that incorrect, or the way I understand next()
The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
jQuery DOM Traversing Get next element To get the next element you can use the . next() method. If you are standing on the "Anna" element and you want to get the next element, "Paul", the . next() method will allow you to do that.
The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
Use the querySelectorAll() method to get all elements by type, e.g. document. querySelectorAll('input[type="text"]') . The method returns a NodeList containing the elements that match the provided selector.
.next() only looks at the next sibling Element in the DOM. IE.
$('.day-spin-month').next('input');
Won't match anything since the next sibling is a span, not an input.
nextAll() looks at all the next siblings, so you want:
$(this).nextAll('input').first().focus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With