jQuery 提交时停止表单刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19454310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop form refreshing page on submit
提问by M_Willett
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
在字段中没有任何数据的情况下按下发送按钮时,我将如何防止页面刷新?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
验证设置工作正常,所有字段都变为红色,但页面会立即刷新。我对JS的了解比较基础。
In particular I think the processForm()
function at the bottom is 'bad'.
特别是我认为processForm()
底部的功能是“坏的”。
HTML
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
回答by Overcode
You can prevent the form from submitting with
您可以阻止表单提交
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault()
will stop the submit.
当然,在该函数中,您可以检查空字段,如果有任何不正确的地方,e.preventDefault()
将停止提交。
Without jQuery:
没有 jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
回答by user3413723
Add this onsubmit="return false" code:
添加这个 onsubmit="return false" 代码:
<form name="formname" onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify
那为我修好了。它仍然会运行你指定的 onClick 函数
回答by Vicky Gonsalves
Replace button type to button
:
将按钮类型替换为button
:
<button type="button">My Cool Button</button>
回答by safeer008
You can use this code for form submission without a page refresh. I have done this in my project.
您可以使用此代码提交表单而无需刷新页面。我在我的项目中做到了这一点。
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
回答by arunavkonwar
One great way to prevent reloading the page when submitting using a form is by adding return false
with your onsubmit attribute.
使用表单提交时防止重新加载页面的一种好方法是添加return false
onsubmit 属性。
<form action="#" onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
回答by Mathias Zaja
This problem becomes more complex when you give the user 2 possibilities to submit the form:
当你给用户两种提交表单的可能性时,这个问题变得更加复杂:
- by clicking on an ad hoc button
- by hitting Enter key
- 通过点击一个特别的按钮
- 通过按 Enter 键
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
在这种情况下,您将需要一个功能来检测按下的键,如果按下 Enter 键,您将在其中提交表单。
And now comes the problem with IE (in any case version 11) Remark: This issue does not exist with Chrome nor with FireFox !
现在出现了 IE 的问题(无论如何版本 11) 备注:Chrome 和 FireFox 都不存在此问题!
- When you click the submit button the form is submitted once; fine.
- When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
- 当您单击提交按钮时,表单提交一次;美好的。
- 当您按 Enter 时,表单被提交两次......并且您的 servlet 将被执行两次。如果您没有 PRG(后重定向获取)架构服务器端,结果可能会出乎意料。
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks. This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
尽管解决方案看起来微不足道,但我花了很多时间来解决这个问题,所以我希望它对其他人有用。该解决方案已在 IE (v 11.0.9600.18426)、FF (v 40.03) 和 Chrome (v 53.02785.143 m 64 位) 上成功测试
The source code HTML & js are in the snippet. The principle is described there. Warning:
源代码 HTML 和 js 位于代码段中。那里描述了原理。警告:
You can't test it in the snippet because the post action is not defined and hitting Enter key might interfer with stackoverflow.
您无法在代码段中对其进行测试,因为未定义发布操作并且按 Enter 键可能会干扰 stackoverflow。
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
如果您遇到这个问题,那么只需将 js 代码复制/粘贴到您的环境中并使其适应您的上下文。
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
回答by Deke
In pure Javascript, use: e.preventDefault()
在纯 Javascript 中,使用: e.preventDefault()
e.preventDefault()
is used in jquery but works in javascript.
e.preventDefault()
在 jquery 中使用,但在 javascript 中工作。
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
回答by xyz xyz
The best solution is onsubmit call any function whatever you want and return false after it.
最好的解决方案是 onsubmit 调用任何你想要的函数并在它之后返回 false。
onsubmit="xxx_xxx(); return false;"
回答by ambrosechua
Most people would prevent the form from submitting by calling the event.preventDefault()
function.
大多数人会通过调用event.preventDefault()
函数来阻止表单提交。
Another means is to remove the onclick attribute of the button, and get the code in processForm()
out into .submit(function() {
as return false;
causes the form to not submit. Also, make the formBlaSubmit()
functions return Boolean based on validity, for use in processForm();
另一种方法是删除按钮的 onclick 属性,并将代码processForm()
放入.submit(function() {
asreturn false;
导致表单不提交。此外,使formBlaSubmit()
函数根据有效性返回布尔值,以用于processForm();
katsh
's answer is the same, just easier to digest.
katsh
的答案是一样的,只是更容易消化。
(By the way, I'm new to stackoverflow, give me guidance please. )
(顺便说一下,我是 stackoverflow 的新手,请给我指导。)
回答by sqram
Personally I like to validate the form on submit and if there are errors, just return false.
我个人喜欢在提交时验证表单,如果有错误,就返回 false。
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});