Reputation: 4898
I have a form where I'd like the action of ENTER to move to the next input field instead of submitting the form. I've tried the code below, and a hundred variations, but I'm clearly doing something wrong.
Line 24 always calculates 0 length so 27 never executes. Here it is as text instead of an image:
$('form input').keydown(function(e) {
// The this keyword is <div id="input_form">
if(e.keyCode == 13){
e.preventDefault(); // cancel default 13 key behaviour (submitting form)
var n = $(this).next('input').length;
console.log("nexts=" + n);
if( $(this).next('input').length) { // if there's another field
$(this).next('input').focus(); // move focus to next field in form
}
else {
$(this).blur();
}
}
});
The form is
<form action="" class="my_input_form" enctype="multipart/form-data" id="my_input_form_5" method="post" name="">
<!-- First Name -->
<div id="first_name_wrap" class="field_wrap" >
<label for="first_name" id="first_name_label" class="form_label">First Name</label>
<br />
<input id="first_name" class="field_input" name="first_name" placeholder="" type="text" value="<?php echo $first_name?>">
<div class="form_field_error" id="first_name_error" style="display:none;"></div>
</div>
<!-- Last Name -->
<div id="last_name_wrap" class="field_wrap">
<label for="last_name" id="last_name_label" class="form_label">Last Name</label>
<br />
<input id="last_name" class="field_input" name="last_name" placeholder="" type="text" value="<?php echo $last_name?>">
<div class="form_field_error" id="last_name_error" style="display:none;"></div>
</div>
Does anyone see the problem?
Upvotes: 0
Views: 246
Reputation: 6646
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
You have a parent div first, which means .next("input")
is empty, because there is no sibling element. You need to do something like:
$(this).parent().next(".field_wrap").find("input").length
This will:
$(this)
class="field_wrap"
)Upvotes: 1