<div class="form-style-5">
<form action="send-sms.php" method="POST">
<fieldset>
<legend><span class="number">1</span> Your Information</legend>
<input type="text" name="field1" id="name" placeholder="Your Name *">
<input type="email" name="field2" id="contact"placeholder="Contact Information (Email, Phone Number, etc.) *">
<input type="location" name="field3" id="location" placeholder="Your Location (i.e. McNutt, Hodge Hall, exact address, etc.)*">
<input type="text" name="field4" id="misc" placeholder="Miscellaneous Information That May Be Important"></textarea>
<label for="job">Urgency:</label>
<select id="job" name="field5">
<optgroup label="Urgency level: just for us to prioritize properly">
<option value="Not Urgent">Low (ETA: Up to an hour)</option>
<option value="reading">Normal (ETA: Up to 45 mins)</option>
<option value="boxing">Critical (ETA: ASAP!)</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<legend><span class="number">2</span>Task that needs completion</legend>
<input type="text" id="task" name="field6" placeholder="Let Us Know How We Can Help!*"></input>
</fieldset>
<input name="submit" type="submit" value="Submit" onClick="push();validateForm();"/>
</form>
</div>
我正在使用简单的JS验证功能,它被称为“onClick”我的提交按钮。如果有人提交空表单,我的错误消息会正确显示,但是,一旦您在该警报上按“确定”,表单仍会被提交。我有一个不同形式的类似验证系统,它运行顺畅....我的代码的任何修改,即使它不能解决整体问题,将不胜感激。
function validateForm() {
var errormessage = "";
if (document.getElementById('name').value == "") {
errormessage += "Please enter your name. \n";
document.getElementById('name').style.borderColor = "red";
}
if (document.getElementById('contact').value == "") {
errormessage += "Please enter your contact. \n";
document.getElementById('contact').style.borderColor = "red";
}
if (document.getElementById('location').value == "") {
errormessage += "Tell us where to come! \n";
document.getElementById('location').style.borderColor = "red";
}
if (document.getElementById('task').value == "") {
errormessage += "Tell us how we can help! \n";
document.getElementById('task').style.borderColor = "red";
}
if (errormessage != "") {
alert(errormessage);
return false;
}
return true;
};
答案 0 :(得分:0)
为了阻止表单提交,必须停止事件。点击处理程序设置将冒泡到提交,因为它没有提供停止事件的方法。
一种简单的方法是返回false,正如您在所示函数中所尝试的那样。但是,没有使用该返回值。请注意,您的内联事件处理程序如下所示
onClick="push();validateForm();"
由于从未使用validateForm的值,因此事件处理程序在调用验证后继续。修复是使用返回值
onClick="push();return validateForm();"
如果验证失败,现在将正确停止该事件。