Submit form on Enter key with javascript

2019-01-14 12:07发布

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>

7条回答
混吃等死
2楼-- · 2019-01-14 12:34

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"

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-14 12:35

Oh that is because the HTML form element does not recognize the link as a button, to click.. you need to replace it with a button...

<input type="submit" value="this will display on your button" onClick="javascript:void(0)">

but if you want it to look like a link you should do this in the css

<style type="text/css">
input{background-color:white;border:0 none;}
</style>
查看更多
等我变得足够好
4楼-- · 2019-01-14 12:41
// Process form if use enter key. put script in head.    
document.onkeyup = enter;    
function enter(e) {if (e.which == 13) submitForm();}

// uses keyup not down as better practice imo    
// submitForm() is user function that posts the form
查看更多
唯我独甜
5楼-- · 2019-01-14 12:45

Try this:

document.getElementById('email').onkeydown = function(e){
   if(e.keyCode == 13){
     // submit
   }
};
查看更多
虎瘦雄心在
6楼-- · 2019-01-14 12:46

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

查看更多
小情绪 Triste *
7楼-- · 2019-01-14 12:59

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>
查看更多
登录 后发表回答