这样我就能更好地理解如何编写preventDefault而不是返回false。这是一个返回false的示例。我想使用preventDefault
重写此代码我的HTML:
<form name="myForm" action="formPracticePHP.php" method="post" onsubmit="return validateForm()">
<p>Enter your Name: <input type="text" name="name" value="" placeholder="[your-name]" required="required" /><br /></p>
<p>Enter your Age: <input type="number" name="age" size="6" value="" /><br /></p>
<p>Please Select Your Favorite Fruit</p>
<select name="fruit" id="fruit">
<option value="nothing" selected="selected">Select A Fruit</option>
<option value="Bannana">Bannana</option>
<option value="Kiwi">Kiwi</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Cherry">Cherry</option>
</select>
<input type="submit" name="submit" value="submit" id="submitBtn" />
</form>
我的JavaScript
function validateForm() {
var x = document.forms["myForm"]["age"].value;
var x2 = document.forms["myForm"]["fruit"].value;
if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
alert("Age and fruit selection must be filled out");
return false;
}
}
答案 0 :(得分:2)
您必须将event
参数传递给您的处理程序
<form onsubmit="validateForm(event)" >
改变你的功能
function validateForm(e) {
var x = document.forms["myForm"]["age"].value;
var x2 = document.forms["myForm"]["fruit"].value;
if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
e.preventDefault();
alert("Age and fruit selection must be filled out");
}
}
如果您从JavaScript设置处理程序,则上述相同的功能也可以使用。
答案 1 :(得分:1)
假设validateForm
已注册为表单的onsubmit
处理程序,您应该可以执行此操作:
function validateForm(e) {
var x = document.forms["myForm"]["age"].value;
var x2 = document.forms["myForm"]["fruit"].value;
if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
alert("Age and fruit selection must be filled out");
e.preventDefault(); // here
}
}
如果您在HTML中使用onsubmit
属性来执行此操作,则可以删除return
部分,然后您需要将事件传递给它:
onsubmit="validateForm(event)"
但是,我强烈建议不要使用HTML属性来指定事件处理程序,而是使用JavaScript代码注册处理程序:
window.onload = function () {
document.forms["myForm"].addEventListener("onsubmit", validateForm);
};