Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move the cursor to the next field and not submitting the form on enter

what im trying to do is that when i press enter key the focus(cursor) moves to the next input field, and im getting that. in the code below i've set the submit of form false when enter is press so that the form would not submitted on enter. but as a result the form is not even submitted when i click on the submit button. All i need is on enter my cursor moves to the next input field and the form will submit on click on the button. i hope it will make sense to you..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
$(document).ready(function() {

$('.username').keypress(function (e) {
     if (e.which === 13) {
         var index = $('.username').index(this) + 1;
         $('.username').eq(index).focus();
     }
 });

});
</script>

</head>

<body>
<div class="test">
<form method="POST" id="form">
<input type="text" class="username" onkeypress="sheikh(event)">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="submit" value="Submit"  class="username">
</form>
</div>
<script>
function sheikh(e){
var key;
if(e.which == 13){
    document.getElementById("form").onsubmit=function (){
    return false;
}
    }
    else{
        document.getElementById("form").onsubmit=function (){
    return true;
}

        }


}

</script>
</body>
</html>
like image 802
ItWorksOnLocal Avatar asked Feb 03 '26 03:02

ItWorksOnLocal


1 Answers

Use this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function() {

$('.username').keypress(function (e) {
     if (e.which === 13) {
         e.preventDefault();
         var index = $('.username').index(this) + 1;
         $('.username').eq(index).focus();
     }
 });
  

});
</script>

</head>

<body>
<div class="test">
<form method="POST" action="http://google.es" id="form">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="text" class="username">
<input type="submit" value="Submit"  class="username">
</form>
</div>
</body>
</html>
like image 163
Marcos Pérez Gude Avatar answered Feb 04 '26 17:02

Marcos Pérez Gude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!