好的伙计们,我正在尝试使用JavaScript来验证表单,然后在使用正确的信息对其进行验证后显示“谢谢”消息。我已经开始验证名字,电子邮件地址和电台选择,但是我似乎无法验证状态选择,或显示感谢信息,但我也使用了我的浏览器(Firefox)Dev Console挖掘语法错误。没有显示。有什么帮助吗?
下面是一小段代码,一个指向整个代码的jsfiddle链接,加上HTML就在下面。
function validForm() { // reference point
/* first name, email, comments and phone */
var fname = document.form1.fname;
var email = document.form1.email;
var comments = document.form1.comments;
var phone1 = document.form1.phone1;
var phone2 = document.form1.phone2;
var phone3 = document.form1.phone3;
/* collecting the error spans for later use */
var fnErr = document.getElementById('fnErr');
var lnErr = document.getElementById('lnErr');
var emErr = document.getElementById('emErr');
var phErr = document.getElementById('phErr');
var cmErr = document.getElementById('cmErr');
var state = document.getElementById('stErr');
if(fname.value=="") {
fnErr.innerHTML = "We need your name, please.";
fname.focus();
return false;
} else {
fnErr.innerHTML = "";
}
if(email.value=="") {
emErr.innerHTML = "We need your email, please.";
email.focus();
return false;
} else {
emErr.innerHTML = "";
}
if(state.value=="none") {
fnErr.innerHTML = "Please select your state.";
state.focus();
return false;
} else {
fnErr.innerHTML = "";
}
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if(isNaN(phone1.value) || isNaN(phone2.value) ||
isNaN(phone3.value)) {
phErr.innerHTML = "If you include a phone number it should be numbers only.";
phone1.select();
return false;
} else {
phErr.innerHTML = "";
}
var notices = document.form1.notices;
var selected;
for(var i=0;i<notices.length;i++) {
if(notices[i].checked) {
selected = notices[i].value;
}
}
/* set up a message for a advert recipient */
var msg = "Thank you, <b>"+fname.value
+"!</b> Your message has been received and one of our representatives will reply to <a href='"
+email.value+"'>"+email.value+"</a> within a day or two. Relax, and enjoy the rest of the site!";
if(selected != undefined) {
document.getElementById('notePref').innerHTML = "";
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}
var contactForm = document.getElementById('registerForm').setAttribute('class','hide');
var loseSep = document.getElementsByClassName('spec');
loseSep[0].setAttribute('class', 'hide');
} else {
document.getElementById('notePref').innerHTML = "Please make a selection:";
}
} // reference point
答案 0 :(得分:1)
首先:你没有地方(div / span / etc),id =&#34; fnlMsg&#34;
第二:你没有地方(div / span / etc),id =&#34; contactForm&#34;
然后更改您的HTML
<select name="state">
与
<select id="state">
和你的脚本
var state = document.getElementById('stErr');
到
var state = document.getElementById('state');
答案 1 :(得分:1)
这是你的罪魁祸首&#39; fnlMsg &#39;元素未定义
Stopping - Gradle Build Running