我对您的 HTML 进行了重构,以便您能够向最终用户反馈,而不会对 alert() 框造成干扰。
<!-- Use ID to attach to in JS -->
<form id="form_units" action="#" method="post">
<div>
<!-- Labels, because... well, labels. -->
<label for="extra_units_4">extra_units_4</label>
<!-- Use data-attr to identify which elements should be validated and how. This future proofs your code, and it's a good pattern to follow. -->
<select id="extra_units_4" data-validate="notempty">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<!-- Hidden element to provide feedback as it's better UX -->
<div class="fielderror">Please make a selection</div>
</div>
<div>
<label for="extra_units_7">extra_units_7</label>
<select id="extra_units_7" data-validate="notempty">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="fielderror">Please make a selection</div>
</div>
<!-- Included an input[type="text"] for fun, and because future proofing is good -->
<div>
<label for="extra_units_8">extra_units_8</label>
<input type="text" id="extra_units_8" data-validate="notempty" />
<div class="fielderror">Please make a selection</div>
</div>
<!-- There appeared to be no reason not to use an input[type="submit"] in your code. Not doing so adds a tiny amount of complexity - so I slimmed the example down. Re-factor yourself for if <button> is a requirement. -->
<input type="submit" class="options-btn" value="Submit" />
</form>
现在我们有一个简单的 JS,它将捕获所有 <input>s 和 data-validate="notempty"。
// Make sure you're specific with your selector for your form
$('#form_units').on('submit',function(e) {
// Hide all .fielderror elements within the context of 'this' form.
// This means that the next time we submit error messages are reset
$('.fielderror', this).hide();
// Select for all 'not empty' validations
$('[data-validate="notempty"]').each(function (index, item) {
// Check if it's an input[type="text"] - future proofing your "not empty" requirements. Expand on this idea for "radio" and "checkbox" inputs if and when required.
if ($(item).attr('type') === 'text') {
// Text is empty if the length is less than one char
if ($(item).val().length < 1) {
// We've found one that is invalid so stop the from from sending
e.preventDefault();
// Show the .fielderror text that is associated with the input being validated
$(item).siblings('.fielderror').show();
}
} else {
// Selects are empty if val() is less than 1. Be warned, this is dependant on having numerical values - and assumes that zero means no answer.
if ($(item).val() < 1) {
// We've found one that is invalid so stop the from from sending
e.preventDefault();
// Show the .fielderror text that is associated with the input being validated
$(item).siblings('.fielderror').show();
}
}
})
});
最后,添加一点 CSS 来隐藏错误消息并在它们显示时设置样式。
.fielderror { display: none; color: red;}
更新 HTML 结构和文本输入的工作示例的 jsFiddle - https://jsfiddle.net/likestothink/xLLvzps2/9/