我试图以最简单的方式验证我的表单,但不知何故不起作用,当我点击提交按钮时,它只是重新加载页面而不在IsRequired类上给出错误消息。
我做错了什么?
HTML5
<form method="post">
<div>
<div class="field-wrap"><label>First Name</label></div>
<input class="thevalue" type="text" minlength="3" style="text-transform:uppercase">
<div class="IsRequired" style="display:none">Fill first name</div>
</div>
<div>
<div class="field-wrap"><label>Second Name</label></div>
<input class="thevalue" type="text" minlength="3" style="text-transform:uppercase">
<div class="IsRequired" style="display:none">Fill second name</div>
</div>
<div>
<div class="field-wrap"><label>email</label></div>
<input class="thevalue" type="text" style="text-transform:lowercase">
<div class="IsRequired" style="display:none">Fill email</div>
</div>
<div>
<div class="field-wrap"><label>Country</label></div>
<select name="Country" class="thevalue cs-select" style="display: none;">
</select>
<div class="IsRequired" style="display:none">Select country</div>
</div>
<div>
<input name="Submit" type="submit" value="Submit">
</div>
</form>
的JavaScript
$(document).ready(function() {
$("form").submit(function(event) {
var bool = false;
var el = document.getElementsByClassName("thevalue");
var el_ = document.getElementsByClassName("IsRequired");
for(var i = 0; i < el.length; i++) {
if(el[i].value == "" || el[i].value == null) {
el_[i].style.display = 'block'; // show message error
bool = true;
} else if(el[i].value != "" || el[i].value != null) {
el_[i].style.display = 'none';
}
}
if(bool == true) {
//no submit without reload
} else if(bool == false) {
//submit
}
event.preventDefault();
})
})
答案 0 :(得分:0)
<强>解决强>
我在@Rupal指定的每个输入字段上放置了必需项,并在@kevinniel的开头放置了e.preventDefault()。
所以,我已将代码更改为:
$('form').submit(function(e) {
e.preventDefault();
$('input[required]').each(function() {
if($(this).val() == '') {
$('span.form_error').text('A required field was not filled out');
}
});
})