简体   繁体   English

停止HTML5表单发布,刷新或在onSubmit上打开一个新窗口

[英]Stop a HTML5 form posting, refreshing or opening a new window onSubmit

I'm using the HTML5 form tag for the client side validator built into it, but I don't want it to submit a thing as I've just got a Javascript function to run instead. 我正在使用内置的客户端验证器的HTML5表单标签,但我不希望它提交一个东西,因为我只是运行Javascript函数。

How can i stop the Post method of the form. 如何停止表单的Post方法。

Cheers - Caius 干杯 - 凯厄斯

add a return false after the function call, like so: 在函数调用后添加一个返回false ,如下所示:

<input .... onclick="function();return false;" />

or you could just return true/false from the function like so: 或者您可以像这样从函数返回true / false:

<input .... onclick="return function()" />

我更倾向于保留我的函数,并在onsubmit处理程序中添加一个返回false,例如:

<form onsubmit="aFunction(); return false;">

If you use jQuery you can do: 如果您使用jQuery,您可以:

$('#your_form_id').submit(function(e){
   e.preventDefault(); 
  // do your staff
});

You can also do it without a framework: 你也可以在没有框架的情况下做到:

document.getElementById('your_form_id').addEventListener('submit' function() {
  // do your staff
  return false;
});

In the "// do your staff" you can write your ajax code. 在“// do your staff”中,您可以编写ajax代码。

I've try all your solution but it still to reload the page after the ajax process : 我已经尝试了所有的解决方案,但仍然需要在ajax进程后重新加载页面:

<form id="form2" method="POST" onsubmit='sent(); return false;' >

function sent(){
    $.ajax({
        ...
    });
}

Add the onsubmit property to your form tag: 将onsubmit属性添加到表单标记:

<form onsubmit="return myfunction()">

ensure you return a bool for your function 确保你为你的功能返回一个bool

function myfunction() {
  // do your validation
  if (validation.passes)  { // you will need to change this line !!!
     return true; // to submit
  } else {
     return false; // to prevent submit
  }
}

Add a onsubmit handler to your form, eg 在表单中添加一个onsubmit处理程序,例如

<form method="POST" onsubmit="return sendForm();">

Then define the function and add false as return value: 然后定义函数并将false添加为返回值:

function sendForm() {
    //do your ajax request...
    return false;
}

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

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