点击提交按钮后,表单会转到操作页面" formsubmit.html"没有填空......
HTML:
<form name="myForm" action="formsubmit.html" method="POST" enctype="multipart/form-data" onsubmit="return validateForm()">
JAVASCRIPT(Jquery):
$(function () {
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name == null || name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
if (email == null || email == "") {
alert("email required");
return false;
}
var phone = document.forms["myForm"]["phone"].value;
if (phone == null || phone == "") {
alert("please enter a valid phone number");
return false;
}
var subject = document.forms["myForm"]["subject"].value;
if (subject == null || subject == "") {
alert("You forgot your message!");
return false;
}
}
});
答案 0 :(得分:2)
当您使用validateForm()
事件处理程序时,需要将jQuery块的on*
函数移到之外。如果您检查控制台,则可能会出现错误,指出您的功能未定义,因为它超出了范围。试试这个:
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name == null || name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
if (email == null || email == "") {
alert("email required");
return false;
}
var phone = document.forms["myForm"]["phone"].value;
if (phone == null || phone == "") {
alert("please enter a valid phone number");
return false;
}
var subject = document.forms["myForm"]["subject"].value;
if (subject == null || subject == "") {
alert("You forgot your message!");
return false;
}
}
$(function () {
// jQuery code here..
});
更好的是,摆脱过时的on*
属性,并使用不引人注目的JS代码绑定您的事件。
<form name="myForm" id="myForm" action="formsubmit.html" method="POST" enctype="multipart/form-data">
$(function() {
$('#myForm').submit(function(e) {
var name = $('#fname').val().trim();
if (name == null || name == "") {
e.preventDefault();
alert("Name must be filled out");
}
var email = $('#email').val().trim();
if (email == null || email == "") {
e.preventDefault();
alert("email required");
}
var phone = $('#phone').val().trim();
if (phone == null || phone == "") {
e.preventDefault();
alert("please enter a valid phone number");
}
var subject = $('#subject').val().trim();
if (subject == null || subject == "") {
e.preventDefault();
alert("You forgot your message!");
}
}
});
答案 1 :(得分:0)
你的函数在一个未命名的函数闭包中,它应该全局定义:
// global scope
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name == null || name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
if (email == null || email == "") {
alert("email required");
return false;
}
var phone = document.forms["myForm"]["phone"].value;
if (phone == null || phone == "") {
alert("please enter a valid phone number");
return false;
}
var subject = document.forms["myForm"]["subject"].value;
if (subject == null || subject == "") {
alert("You forgot your message!");
return false;
}
}