I need to move in to the next input field inside a table with many rows using enter key press. I try this :
$(function() {
$('input').keyup(function (e) {
if (e.which == 13) {
$(this).find().next('input').focus();
}
});
});
Why dont work ? :(
HTML
<table class="half">
<tr>
<td>Nome :</td>
<td><input name="ragsoc" type="text" id="ragsoc" value=""/></td>
<td>Mnemo:</td>
<td><input name="mnemo" type="text" id="mnemo" value=""/></td>
<td>Partita IVA :</td>
<td><input name="piva" type="text" id="piva" value=""/></td>
</tr>
<tr>
<td>Nome :</td>
<td><input name="ragsoc" type="text" id="ragsoc" value=""/></td>
<td>Mnemo:</td>
<td><input name="mnemo" type="text" id="mnemo" value=""/></td>
<td>Partita IVA :</td>
<td><input name="piva" type="text" id="piva" value=""/></td>
</tr>
</table>
This code work fine but only in the first row of table :
$('input').keydown(function (e) {
if (e.which === 13) {
$(this).closest('td').nextAll().eq(1).find('input').focus()
}
});
What is wrong or missing ?
Assuming .inputs
is a sibling of your current element. .find()
searches in descendants of current element(this)
$('.inputs').keydown(function (e) {
if (e.which === 13) {
$(this).next('.inputs').focus();
}
});
You need to use .closest(), .nextAll()
$('.inputs').keydown(function (e) {
if (e.which === 13) {
$(this).closest('td').nextAll().eq(1).find('.inputs').focus();
//OR
//$(this).closest('td').next().next().find('.inputs').focus()
}
});
DEMO
As OP has updated question. Use
$('.inputs').keydown(function (e) {
if (e.which === 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
DEMO, As note I have used class="inputs"
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