简体   繁体   English

添加JS代码后按钮提交两次防止多次点击

[英]Button submitting twice after adding JS code to prevent multiple clicking

I have added the below onclick code to the submit button in order to prevent users from submitting several times by clicking quickly on the button.我已将以下onclick代码添加到提交按钮,以防止用户通过快速单击按钮多次提交。

<button type="submit" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" class="btn btn-primary" align="right">Submit</button>

After doing this addition, I noticed that the button is submitting two times instead of once.完成此添加后,我注意到按钮提交了两次而不是一次。 How can I fix this ?我怎样才能解决这个问题 ?

Extending @Nico_ 's answer, one option would be to change the button type to type="button" and it would submit only when you decide to submit the function.扩展@Nico_ 的答案,一种选择是将按钮类型更改为type="button"并且仅在您决定提交该功能时才会提交。

The other option would be to assign a JS function instead of doing everything in onclick .另一种选择是分配一个 JS 函数,而不是在onclick中做所有事情。

An example could be:一个例子可能是:

<button id="button1" type="submit" onclick="submitAction(event)">

<script>
function submitAction(e) {
   e.preventDefault();
   document.getElementById("button1").disabled = true;
   document.getElementById("button1").value = 'Sending, please wait...';
   this.form.submit();
}
</script>

It's because your button has a type "submit" so if the user press it, whatever is your onclick, the form will be submited since your onclick do that too, the form is submited twice.这是因为您的按钮具有“提交”类型,因此如果用户按下它,无论您的 onclick 是什么,表单都将被提交,因为您的 onclick 也会这样做,表单被提交两次。 You can fix that by removing the type.您可以通过删除类型来解决该问题。

Either add return false;要么添加return false; at the end of your inline Javascript event listener:在您的内联 Javascript 事件侦听器的末尾:

<button type="submit" 
  onclick="this.disabled=true; this.value='Sending, please wait...'; this.form.submit(); return false;" class="btn btn-primary" align="right">Submit</button>

or simply omit this.form.submit();或者干脆省略this.form.submit(); (because that is what a submit button already does by itself when clicked): (因为这是提交按钮在单击时已经自行执行的操作):

<button type="submit" 
  onclick="this.disabled=true; this.value='Sending, please wait...';" class="btn btn-primary" align="right">Submit</button>

I would suggest you to disable the button by adding a disabled attribute to it once the user has submitted the form.我建议您在用户提交表单后通过向其添加禁用属性来禁用该按钮。

You can submit a form using javascript using form.submit();您可以使用 javascript 提交表单,使用form.submit(); . . This way you can remove type="submit" and allows you to have more freedom in controlling the behaviour of onClick event.通过这种方式,您可以删除 type="submit" 并允许您在控制 onClick 事件的行为方面有更多的自由。

For example:例如:

 function myFunction() { document.getElementById("myBtn").disabled = true; }
 <button id="myBtn"onclick="myFunction()">Clickable once only.</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM