RhysE96
RhysE96

Reputation: 197

Enter key doesn't activate button

I have a form with one field that the user needs to type into, and a button underneath that when clicked, does some jQuery and hides the login-form. But when I hit enter after typing something in, the page refreshes...

There's part of me that thinks it doesn't need to be an <input> or a <form>

I don't actually need to post anything. I have tried changing the input to a <button> which completely ruins my styling and still doesn't work. What's the best way of getting round this?

<div class="login-page">
    <div class="form">
    <form class="login-form" method="POST">

   <!-- user inputs -->
   <p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />

   <!-- your submit button -->
   <input class="login" type="button" id="submit" value="login">
</div>

Upvotes: 0

Views: 1568

Answers (4)

RhysE96
RhysE96

Reputation: 197

Don't think i explained it very well but i have fixed it, the enter key now activates the submit button rather than refresh the page.

$("form").submit(function() { return false; });

$(document).ready(function(){
    $('#username').keypress(function(e){
      if(e.keyCode==13)
      $('#submit').click();
    });
});

Upvotes: 0

rorymorris89
rorymorris89

Reputation: 1199

If the enter key is pressed when focused to an input field inside a form that has a submit button, the default browser behaviour is to fire a submit event on that form. You can prevent this happening by either:

return false; or e.preventDefault();

Full code:

$('.login-form').on('submit', function() {
    return false;
});

Fiddle: https://jsfiddle.net/nc1e2gm6/

Bear in mind that if you go down the route of using e.preventDefault(); instead or return false;, you need to pass the e variable from the function call, like:

$('.login-form').on('submit', function(e) { ...

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

You need to attach keypress event to the form or at least the field. For convenience, you also need to combine the callback functions into one.

$('#username').on('keypress', function(event){
    var code = event.keyCode || event.which;
    if(code == 13){ 
        // submit the form.
    }
});

$('#username').on('keypress', function(event){
    var code = event.keyCode || event.which;
    if(code == 13){ 
        console.log('Submitting form');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="login-form" method="POST">
   <p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
   <input class="login" type="button" id="submit" value="login">
</form>

Upvotes: 0

heinkasner
heinkasner

Reputation: 425

True, Adam. If the form does not contain the type submit button, a keypress event has to be added manually. Otherwise Enter will act as the Accept Button on the form.

Upvotes: 1

Related Questions