Submit form on Enter key with javascript

98,811

Solution 1

Try this:

document.getElementById('email').onkeydown = function(e){
   if(e.keyCode == 13){
     // submit
   }
};

Solution 2

Please use below code snippet...It should be added into script block

<script>
    document.onkeydown=function(evt){
        var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
        if(keyCode == 13)
        {
            //your function call here
        }
    }
</script>

Solution 3

All below codes should be added into script block or file. define submit function:

function submitForm(){
    document.priceOptionForm.submit();
    document.priceOptionForm.method='post';
}

For the enter key to submit form:

document.onkeydown=function(){
    if(window.event.keyCode=='13'){
        submitForm();
    }
}

For the link to work:

document.getElementById("profile_price").onclick=submitForm;

You can refer to http://jsfiddle.net/honglonglong/YMX2q/ for some trying.

Solution 4

Use an <input type="submit"> instead of a link. Then the enter key will work automatically.

Solution 5

simply make a hidden button like this
HTML

<input type="submit" id="submitbtn"  />

CSS

#submitbtn{display:none;}

when the user will hit the enter button the form will be submitted
Don't forget to put the type="submit"

Share:
98,811

Related videos on Youtube

Mauro Golin
Author by

Mauro Golin

Updated on July 29, 2022

Comments

  • Mauro Golin
    Mauro Golin almost 2 years

    I'm not sure what I am doing wrong here. I want the enter key to work as well as clicking the button.

    <form action="" method="get" class="priceOptionForm" name="priceOptionForm">
    <input name="paypal_email" type="text" value="whatever" id="email"></label>
    <a href="javascript:void(0);" class="bluebtn" id="profile_price" style="width:60px;margin-top:5px;">Save all</a>
    </form>
    
  • Boontawee Home
    Boontawee Home over 8 years
    <input type="submit" style="display: none;" />
  • Nandhu
    Nandhu over 4 years
    if you want to do code behind refer below this.Form.DefaultButton = "Button1";
  • statosdotcom
    statosdotcom almost 2 years
    Nice, but beware if you have some kind of javascript validation attached to the "onSubmit" of your form.