如何防止按钮提交表单

时间:2022-08-17 00:03:28

In the following page, with Firefox the remove button submits the form, but the add button doesn't. How do I prevent the remove button from submitting the form?

在下面的页面中,使用Firefox,删除按钮提交表单,但是添加按钮不提交表单。如何防止删除按钮提交表单?

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function addItem() {
  var v = $('form :hidden:last').attr('name');
  var n = /(.*)input/.exec(v);
  var newPrefix;
  if ( n[1].length == 0 ) {
    newPrefix = '1';
  } else {
    newPrefix = parseInt(n[1])+1;
  }
  var oldElem = $('form tr:last');
  var newElem = oldElem.clone(true);
  var lastHidden = $('form :hidden:last');
  lastHidden.val(newPrefix);
  var pat = '=\"'+n[1]+'input';
  newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"'+newPrefix+'input'));
  newElem.appendTo('table');
  $('form :hidden:last').val('');
}
function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    rows[rows.length-1].html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}
</script>
</head>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>

<tr>
  <td><input type="text" id="input1" name="input1" /></td>
  <td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>

15 个解决方案

#1


1228  

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

您正在使用HTML5按钮元素。请记住,原因是这个按钮具有提交的默认行为,如在这里看到的W3规范中所述:W3C HTML5按钮

So you need to specify its type explicitly:

因此需要明确指定它的类型:

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

为了覆盖默认提交类型。我只是想指出为什么会发生这种情况=)

=)

=)

#2


549  

Set the type on your buttons:

设置按钮上的类型:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:

…这将防止在事件处理程序中发生异常时触发提交操作。然后,修复removeItem()函数,使其不会引发异常:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.

注意变化:您的原始代码从jQuery集合中提取了一个HTML元素,然后尝试在其上调用一个jQuery方法——这会抛出一个异常,导致按钮的默认行为。

FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:

FWIW,还有另一种方法……使用jQuery连接事件处理程序,并使用jQuery事件对象上的preventDefault()方法提前取消默认行为:

$(function() // execute once the DOM has loaded
{

  // wire up Add Item button click event
  $("#AddItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
  });

  // wire up Remove Last Item button click event
  $("RemoveLastItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of remove last logic
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.

这种技术将所有逻辑保存在一个地方,使调试更容易……它还允许您通过更改按钮上的类型来实现回退,以提交和处理事件服务器端——这就是众所周知的不引人注意的JavaScript。

#3


27  

Sometime ago I needed something very similar... and I got it.

以前我需要一些非常相似的东西……我明白了。

So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).

因此,我在这里所做的是,我如何做这些技巧,使一个表单能够通过JavaScript提交,而不需要验证,只有当用户按下按钮(通常是发送按钮)时才执行验证。

For the example I will use a minimal form, only with two fields and a submit button.

对于本例,我将使用一个最小表单,只有两个字段和一个submit按钮。

Remember what is wanted: From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.

记住需要什么:从JavaScript中,它必须能够在不进行任何检查的情况下提交。但是,如果用户按下这样的按钮,验证必须完成,只有通过验证后才能发送表单。

Normally all would start from something near this (I removed all extra stuff not important):

通常情况下,所有的东西都会从附近的东西开始(我去掉了所有多余的东西):

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>

See how form tag has no onsubmit="..." (remember it was a condition not to have it).

查看表单标签如何没有onsubmit="…"(记住,这是一种不具备的条件)。

The problem is that the form is always submitted, no matter if onclick returns true or false.

问题是,无论onclick返回true还是false,表单总是被提交。

If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.

如果我将type="submit"改为type="button",它似乎可以工作,但不是。它从不发送表单,但这很容易做到。

So finally I used this:

最后我用了这个

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>

And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:

在函数验证器上,返回True;我还添加了一个JavaScript提交语句,类似于以下内容:

function Validator(){
   //  ...bla bla bla... the checks
   if(                              ){
      document.getElementById('theFormID').submit();
      return(true);
   }else{
      return(false);
   }
}

The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.

id=""只是用于JavaScript getElementById, name=""只是用于在POST数据上显示。

On such way it works as I need.

这样它就能按我的需要工作了。

I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.

我只是针对那些不需要在表单上使用onsubmit函数的人,但是在用户按下按钮时进行一些验证。

Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.

为什么我不需要onsubmit表单标签?很简单,在其他JavaScript部分,我需要执行提交,但我不希望有任何验证。

The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.

原因是:如果用户执行了我想要的提交,并且需要进行验证,但是如果是JavaScript,有时我需要执行提交,而这样的验证可以避免这种情况。

It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!

这听起来可能有些奇怪,但当你想的时候却不是这样。与一些限制…比如不允许使用PHP会话,也不允许使用cookie !

So any link must be converted to such form submit, so the login data is not lost. When no login is yet done, it must also work. So no validation must be performed on links. But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.

因此,任何链接都必须转换为此类表单提交,因此不会丢失登录数据。当没有登录时,它也必须工作。因此,必须在链接上执行验证。但是,如果用户没有同时输入字段、user和pass,我希望向用户显示一条消息。因此,如果一个人丢失了,表格就不能发送!有这个问题。

See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.

请参见问题:当一个字段为空时,只有当用户按下按钮时,才能发送表单,如果是JavaScript代码,则必须能够发送表单。

If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.

如果我对表单标记上的onsubmit进行处理,我需要知道它是用户还是其他JavaScript。由于不能传递任何参数,所以不能直接传递,所以有些人添加了一个变量来判断是否必须进行验证。验证函数的第一件事是检查变量值,等等。太复杂和代码没有说什么是真正需要的。

So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.

所以解决方案不是在表单标签上有onsubmit。欧洲工商管理学院把它放在真正需要的地方。

For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.

另一方面,为什么要放入onsubmit代码,因为从概念上来说,我不需要onsubmit验证。我真的需要按钮验证。

Not only the code is more clear, it is where it must be. Just remember this: - I do not want JavaScript to validate the form (that must be always done by PHP on the server side) - I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)

不仅代码更清晰,它还必须在那里。请记住:-我不希望JavaScript验证表单(必须始终由PHP在服务器端执行)-我希望向用户显示一条消息,告诉用户所有字段不能为空,这需要JavaScript(客户端)

So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?

那么,为什么有些人(认为或告诉我)必须在onsumbit验证上进行验证呢?不,从概念上讲,我不是在客户端进行onsumbit验证。我只是在按钮上做了一些事情,所以为什么不让它实现呢?

Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:

代码和样式很好地完成了这个任务。在任何JavaScript上,我需要发送的表单,我刚刚放:

document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there

And that skips validation when I do not need it. It just sends the form and loads a different page, etc.

当我不需要验证时,就会忽略验证。它只发送表单并加载不同的页面,等等。

But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.

但是,如果用户单击submit按钮(也就是type="button" not type="submit"),则在提交表单之前进行验证,如果无效,则不发送。

Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.

希望这能帮助其他人不要尝试冗长而复杂的代码。如果不需要,就不用onsubmit,并使用onclick。但请记住要将type="submit"改为type="button",请不要忘记使用JavaScript提交()。

#4


22  

I agree with Shog9, though I might instead use:

我同意幕府将军的说法,但我可以用:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools, the <button> tag has different behavior on different browsers.

w3schools表示,

#5


17  

Suppose your HTML form has id="form_id"

假设HTML表单有id="form_id"

<form id="form_id">
<!--your HTML code-->
</form>

Add this jQuery snippet to your code to see result,

将此jQuery代码片段添加到代码中以查看结果,

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

#6


13  

$("form").submit(function () { return false; }); that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/> Which will only work if this button isn't the only button in this form.

$(“形式”)。提交(函数(){返回false;});这将阻止按钮提交,或者您可以将按钮类型改为“button”,而不是,只有当这个按钮不是这个表单中唯一的按钮时,这个按钮才能工作。

#7


9  

This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:

如前所述,这是html5的一个错误,您仍然可以将按钮作为提交(如果您想同时包含javascript和非javascript用户)使用,比如:

     <button type="submit" onclick="return false"> Register </button>

This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.

通过这种方式,您将取消提交,但仍然使用jquery或javascript函数执行任何操作,并为没有javascript的用户执行提交。

#8


7  

I am sure that on FF the

我敢肯定

removeItem 

function encounter a JavaScript error, this not happend on IE

函数遇到JavaScript错误,这在IE上是不会发生的

When javascript error appear the "return false" code won't run, making the page to postback

当出现javascript错误时,“返回false”代码不会运行,使页面回发

#9


2  

Here's a simple approach:

这里有一个简单的方法:

$('.mybutton').click(function(){

    /* Perform some button action ... */
    alert("I don't like it when you press my button!");

    /* Then, the most important part ... */
    return false;

});

#10


2  

return false;

You can return false at the end of the function or after the function call.

可以在函数末尾或函数调用之后返回false。

Just as long as it's the last thing that happens, the form will not submit.

只要它是最后发生的事情,表单就不会提交。

#11


1  

The following sample code show you how to prevent button click from submitting form.

下面的示例代码展示了如何防止按钮单击提交表单。

You may try my sample code:

您可以试试我的示例代码:

 <form autocomplete="off" method="post" action="">
   <p>Title:
     <input type="text" />
   </p>
   <input type="button" onclick="addItem()" value="Add Item">
   <input type="button" onclick="removeItem()" value="Remove Last Item">
   <table>
     <th>Name</th>

     <tr>
       <td>
         <input type="text" id="input1" name="input1" />
       </td>
       <td>
         <input type="hidden" id="input2" name="input2" />
       </td>
     </tr>
   </table>
   <input id="submit" type="submit" name="submit" value="Submit">
 </form>
<script language="javascript">
function addItem() {
return false;
}

function removeItem() {
return false;
}
</script>

#12


1  

Set your button in normal way and use event.preventDefault like..

按正常方式设置按钮并使用事件。preventDefault像. .

   <button onclick="myFunc(e)"> Remove </button>  
   ...
   ...

   In function...

   function myFunc(e){
       e.preventDefault();
   }

#13


0  

I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.

我现在还不能测试这个,但是我认为您可以使用jQuery的preventDefault方法。

#14


0  

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

removeItem函数实际上包含一个错误,这使得表单按钮执行默认行为(提交表单)。在这种情况下,javascript错误控制台通常会给出一个指针。

Check out the function removeItem in the javascript part:

查看javascript部分的函数removeItem:

The line:

线:

rows[rows.length-1].html('');

doesn't work. Try this instead:

是行不通的。试试这个:

rows.eq(rows.length-1).html('');

#15


0  

You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:

您只需使用jQuery获取按钮的引用,并阻止其传播,如下所示:

 $(document).ready(function () {
    $('#BUTTON_ID').click(function(e) {

            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            return false;
    });});

#1


1228  

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

您正在使用HTML5按钮元素。请记住,原因是这个按钮具有提交的默认行为,如在这里看到的W3规范中所述:W3C HTML5按钮

So you need to specify its type explicitly:

因此需要明确指定它的类型:

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

为了覆盖默认提交类型。我只是想指出为什么会发生这种情况=)

=)

=)

#2


549  

Set the type on your buttons:

设置按钮上的类型:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:

…这将防止在事件处理程序中发生异常时触发提交操作。然后,修复removeItem()函数,使其不会引发异常:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.

注意变化:您的原始代码从jQuery集合中提取了一个HTML元素,然后尝试在其上调用一个jQuery方法——这会抛出一个异常,导致按钮的默认行为。

FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:

FWIW,还有另一种方法……使用jQuery连接事件处理程序,并使用jQuery事件对象上的preventDefault()方法提前取消默认行为:

$(function() // execute once the DOM has loaded
{

  // wire up Add Item button click event
  $("#AddItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
  });

  // wire up Remove Last Item button click event
  $("RemoveLastItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of remove last logic
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.

这种技术将所有逻辑保存在一个地方,使调试更容易……它还允许您通过更改按钮上的类型来实现回退,以提交和处理事件服务器端——这就是众所周知的不引人注意的JavaScript。

#3


27  

Sometime ago I needed something very similar... and I got it.

以前我需要一些非常相似的东西……我明白了。

So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).

因此,我在这里所做的是,我如何做这些技巧,使一个表单能够通过JavaScript提交,而不需要验证,只有当用户按下按钮(通常是发送按钮)时才执行验证。

For the example I will use a minimal form, only with two fields and a submit button.

对于本例,我将使用一个最小表单,只有两个字段和一个submit按钮。

Remember what is wanted: From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.

记住需要什么:从JavaScript中,它必须能够在不进行任何检查的情况下提交。但是,如果用户按下这样的按钮,验证必须完成,只有通过验证后才能发送表单。

Normally all would start from something near this (I removed all extra stuff not important):

通常情况下,所有的东西都会从附近的东西开始(我去掉了所有多余的东西):

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>

See how form tag has no onsubmit="..." (remember it was a condition not to have it).

查看表单标签如何没有onsubmit="…"(记住,这是一种不具备的条件)。

The problem is that the form is always submitted, no matter if onclick returns true or false.

问题是,无论onclick返回true还是false,表单总是被提交。

If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.

如果我将type="submit"改为type="button",它似乎可以工作,但不是。它从不发送表单,但这很容易做到。

So finally I used this:

最后我用了这个

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>

And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:

在函数验证器上,返回True;我还添加了一个JavaScript提交语句,类似于以下内容:

function Validator(){
   //  ...bla bla bla... the checks
   if(                              ){
      document.getElementById('theFormID').submit();
      return(true);
   }else{
      return(false);
   }
}

The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.

id=""只是用于JavaScript getElementById, name=""只是用于在POST数据上显示。

On such way it works as I need.

这样它就能按我的需要工作了。

I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.

我只是针对那些不需要在表单上使用onsubmit函数的人,但是在用户按下按钮时进行一些验证。

Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.

为什么我不需要onsubmit表单标签?很简单,在其他JavaScript部分,我需要执行提交,但我不希望有任何验证。

The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.

原因是:如果用户执行了我想要的提交,并且需要进行验证,但是如果是JavaScript,有时我需要执行提交,而这样的验证可以避免这种情况。

It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!

这听起来可能有些奇怪,但当你想的时候却不是这样。与一些限制…比如不允许使用PHP会话,也不允许使用cookie !

So any link must be converted to such form submit, so the login data is not lost. When no login is yet done, it must also work. So no validation must be performed on links. But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.

因此,任何链接都必须转换为此类表单提交,因此不会丢失登录数据。当没有登录时,它也必须工作。因此,必须在链接上执行验证。但是,如果用户没有同时输入字段、user和pass,我希望向用户显示一条消息。因此,如果一个人丢失了,表格就不能发送!有这个问题。

See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.

请参见问题:当一个字段为空时,只有当用户按下按钮时,才能发送表单,如果是JavaScript代码,则必须能够发送表单。

If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.

如果我对表单标记上的onsubmit进行处理,我需要知道它是用户还是其他JavaScript。由于不能传递任何参数,所以不能直接传递,所以有些人添加了一个变量来判断是否必须进行验证。验证函数的第一件事是检查变量值,等等。太复杂和代码没有说什么是真正需要的。

So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.

所以解决方案不是在表单标签上有onsubmit。欧洲工商管理学院把它放在真正需要的地方。

For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.

另一方面,为什么要放入onsubmit代码,因为从概念上来说,我不需要onsubmit验证。我真的需要按钮验证。

Not only the code is more clear, it is where it must be. Just remember this: - I do not want JavaScript to validate the form (that must be always done by PHP on the server side) - I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)

不仅代码更清晰,它还必须在那里。请记住:-我不希望JavaScript验证表单(必须始终由PHP在服务器端执行)-我希望向用户显示一条消息,告诉用户所有字段不能为空,这需要JavaScript(客户端)

So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?

那么,为什么有些人(认为或告诉我)必须在onsumbit验证上进行验证呢?不,从概念上讲,我不是在客户端进行onsumbit验证。我只是在按钮上做了一些事情,所以为什么不让它实现呢?

Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:

代码和样式很好地完成了这个任务。在任何JavaScript上,我需要发送的表单,我刚刚放:

document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there

And that skips validation when I do not need it. It just sends the form and loads a different page, etc.

当我不需要验证时,就会忽略验证。它只发送表单并加载不同的页面,等等。

But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.

但是,如果用户单击submit按钮(也就是type="button" not type="submit"),则在提交表单之前进行验证,如果无效,则不发送。

Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.

希望这能帮助其他人不要尝试冗长而复杂的代码。如果不需要,就不用onsubmit,并使用onclick。但请记住要将type="submit"改为type="button",请不要忘记使用JavaScript提交()。

#4


22  

I agree with Shog9, though I might instead use:

我同意幕府将军的说法,但我可以用:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools, the <button> tag has different behavior on different browsers.

w3schools表示,

#5


17  

Suppose your HTML form has id="form_id"

假设HTML表单有id="form_id"

<form id="form_id">
<!--your HTML code-->
</form>

Add this jQuery snippet to your code to see result,

将此jQuery代码片段添加到代码中以查看结果,

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

#6


13  

$("form").submit(function () { return false; }); that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/> Which will only work if this button isn't the only button in this form.

$(“形式”)。提交(函数(){返回false;});这将阻止按钮提交,或者您可以将按钮类型改为“button”,而不是,只有当这个按钮不是这个表单中唯一的按钮时,这个按钮才能工作。

#7


9  

This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:

如前所述,这是html5的一个错误,您仍然可以将按钮作为提交(如果您想同时包含javascript和非javascript用户)使用,比如:

     <button type="submit" onclick="return false"> Register </button>

This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.

通过这种方式,您将取消提交,但仍然使用jquery或javascript函数执行任何操作,并为没有javascript的用户执行提交。

#8


7  

I am sure that on FF the

我敢肯定

removeItem 

function encounter a JavaScript error, this not happend on IE

函数遇到JavaScript错误,这在IE上是不会发生的

When javascript error appear the "return false" code won't run, making the page to postback

当出现javascript错误时,“返回false”代码不会运行,使页面回发

#9


2  

Here's a simple approach:

这里有一个简单的方法:

$('.mybutton').click(function(){

    /* Perform some button action ... */
    alert("I don't like it when you press my button!");

    /* Then, the most important part ... */
    return false;

});

#10


2  

return false;

You can return false at the end of the function or after the function call.

可以在函数末尾或函数调用之后返回false。

Just as long as it's the last thing that happens, the form will not submit.

只要它是最后发生的事情,表单就不会提交。

#11


1  

The following sample code show you how to prevent button click from submitting form.

下面的示例代码展示了如何防止按钮单击提交表单。

You may try my sample code:

您可以试试我的示例代码:

 <form autocomplete="off" method="post" action="">
   <p>Title:
     <input type="text" />
   </p>
   <input type="button" onclick="addItem()" value="Add Item">
   <input type="button" onclick="removeItem()" value="Remove Last Item">
   <table>
     <th>Name</th>

     <tr>
       <td>
         <input type="text" id="input1" name="input1" />
       </td>
       <td>
         <input type="hidden" id="input2" name="input2" />
       </td>
     </tr>
   </table>
   <input id="submit" type="submit" name="submit" value="Submit">
 </form>
<script language="javascript">
function addItem() {
return false;
}

function removeItem() {
return false;
}
</script>

#12


1  

Set your button in normal way and use event.preventDefault like..

按正常方式设置按钮并使用事件。preventDefault像. .

   <button onclick="myFunc(e)"> Remove </button>  
   ...
   ...

   In function...

   function myFunc(e){
       e.preventDefault();
   }

#13


0  

I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.

我现在还不能测试这个,但是我认为您可以使用jQuery的preventDefault方法。

#14


0  

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

removeItem函数实际上包含一个错误,这使得表单按钮执行默认行为(提交表单)。在这种情况下,javascript错误控制台通常会给出一个指针。

Check out the function removeItem in the javascript part:

查看javascript部分的函数removeItem:

The line:

线:

rows[rows.length-1].html('');

doesn't work. Try this instead:

是行不通的。试试这个:

rows.eq(rows.length-1).html('');

#15


0  

You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:

您只需使用jQuery获取按钮的引用,并阻止其传播,如下所示:

 $(document).ready(function () {
    $('#BUTTON_ID').click(function(e) {

            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            return false;
    });});