最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hitting enter in any textbox in chrome triggers the form submit, even when there is no submit button - Stack Overfl

programmeradmin4浏览0评论

I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows

<form>
  <input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">

   function validateAndSubmit(){
   //do some validation and then submit 
 }

</script>

In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?

I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows

<form>
  <input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">

   function validateAndSubmit(){
   //do some validation and then submit 
 }

</script>

In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?

Share Improve this question asked Jun 30, 2010 at 9:10 Ritesh M NayakRitesh M Nayak 8,06314 gold badges51 silver badges78 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

use this syntax:

<form onsubmit="return validateAndSubmit()">
...

if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13

Try this method:

<form onsubmit="return validateAndSubmit(this);">
  <input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">

   function validateAndSubmit(form_obj){
     if(some_variable == 'correct_value') {
        form_obj.submit();
        return true;
     } else {
        alert('Wrong value');
        return false;
     }
   //do some validation and then submit 
 }

</script>

I'm not sure if there's a standard regarding this or not.

Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.

So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论