我有一个包含多个输入的表单,在发送之前我检查是否有任何输入为空:
<input type="text" name="number" id="number" style="float:left;clear:both;"/>
<input type="text" name="road" id="road" style="float:left;clear:both;" />
<input type="text" name="town" id="town" style="float:left;clear:both;" />
<input type="submit" name="submit" value="submit" id="submit" />
jquery:
$('#submit').on('click', submitForm);
function submitForm(){
if($('#number, #road, #town').val() ==''){
$('#error-box').show();
$('#error-box p').text('not all fields are complete - please complete to progress');
return false;
}
else{
alert('part 1 complete OK');
$('#add-listing-part1').hide();
$('#add-listing-part2').show();
return false;
}
}
我想在错误框中准确显示哪些字段为空(带有友好的用户友好消息),但我不确定如何在没有if()语句加载的情况下最有效地执行此操作?
逻辑沿着:
答案 0 :(得分:0)
您可以使用此代码:
function submitForm() {
var empty = $('form input[value=""]');
if (empty.length > 0) {
$('#error-box').show();
empty.each(function (index, element) {
$('#error-box p').text($('#error-box p').text() + $(this).attr('name') + ' ');
});
$('#error-box p').text($('#error-box p').text() + 'fields are not filled');
} else {
// complete your submit
}
}