我有一个表单和jquery来在提交之前验证输入。如果我选择品牌=' auto',那么我填写了所需的数据。它不会让我提交表格。我尝试使用Firefox,但它没有显示任何错误。我认为jquery中的if语句存在一些混乱。如果我选择brand =' mobile'则不会发生这种情况。请帮忙......!
以下是jsfiddle
这是我的表格:
<form method='post' id='newpostForm' action='action.php'>
<div id='error'></div>
Title <input type='text' name='title' id='title'>
<select id="brand" name="brand">
<option value="">Select brand</option>
<option value="mobile">Mobile</option>
<option value="auto">Auto</option>
</select>
<div id='morefield' style='display:none'>
<select class=' morefield' id='registeredyear' name='registeredyear'>
<option value=''>Year</option>
<option value='2015'>2015</option>
<option value='2014'>2014</option>
<option value='2013'>2013</option>
</select>
<select class=' morefield' id='km' name='km'>
<option value=''>Km</option>
<option value='0 - 4999'>0 - 4999 km</option>
<option value='5000 - 9999'>5000 - 9999 km</option>
<option value='10000 - 14999'>10000 - 14999 km</option>
</select>
</div>
<button type="submit" name="ok" id="ok" class="btn btn-warning">OK</button>
<form>
这是我的jquery代码:
$(document).ready(function(){
$('#title').focus();
var title = $('#title');
var brand = $('#brand');
var error = $('#error');
var registeredyear = $('#registeredyear');
var km = $('#km');
$("#brand").click(function(){
if (brand.val() == 'auto'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
$('#newpostForm').submit(function(e) {
e.preventDefault();
error.html('');
if (title.val() == ''){
title.focus();
error.html('<span class="errorss"> * Title required</span>');
}
else if (brand.val() == ''){
brand.focus();
error.html('<span class="errorss"> * Brand required</span>');
}
else if (brand.val() == 'auto'){
if(registeredyear.val() == ''){
registeredyear.focus();
error.html('<span class="errorss"> * Registered year required</span>');
}if(km.val()== ''){
km.focus();
error.html('<span class="errorss"> * Km travelled required</span>');
}
}
else {
$('#newpostForm')[0].submit();
}
});
});
答案 0 :(得分:1)
你需要改变一下if / else if if else为了让它工作而编写的意大利面条代码,我建议设置一个标志,以确定你是否应该发送来自,某些东西像这样:
$('#newpostForm').submit(function (e) {
e.preventDefault();
error.html('');
var shouldSend = true;
if (title.val() == '') {
title.focus();
error.html('<span class="errorss"> * Title required</span>');
shouldSend = false;
} else if (brand.val() == '') {
brand.focus();
error.html('<span class="errorss"> * Brand required</span>');
shouldSend = false;
} else if (brand.val() == 'auto') {
if (registeredyear.val() == '') {
registeredyear.focus();
error.html('<span class="errorss"> * Registered year required</span>');
shouldSend = false;
}
if (km.val() == '') {
km.focus();
error.html('<span class="errorss"> * Km travelled required</span>');
shouldSend = false;
}
}
if (shouldSend) $('#newpostForm')[0].submit();
});