对于文本框和数字,如果为空,我们将非常容易地发送以下错误命令:
AJAX
parent_fieldset.find('input[type="text"], input[type="number"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
CSS
.input-error {
border-color: red;
}
但是对于select option
,checkbox
,radio
标签,如果它们为空,我应该怎么办?
答案 0 :(得分:2)
您可以使用以下内容:
$(document).ready(function(){
$('#mySelectBox').each(function() {
if($(this).val() == -1)
$(this).addClass('input-error');
else
$(this).removeClass('input-error');
});
});
小提琴示例here。为了澄清一点,我在这里假设您将拥有一个值为-1的“ please select option”(因此实际上没有选择任何内容):
答案 1 :(得分:2)
要验证是否已选择组合框项目,可以检查 selectedIndex 值。 使用该复选框,可以检查其 checked 属性。
工作示例在https://jsbin.com/hezemohali/edit?html,js,output
function verify() {
let selectCar = this.document.getElementById("car-brand");
if(selectCar.selectedIndex === 0)
selectCar.className = 'input-error';
else
selectCar.classList.remove('input-error');
let tc = this.document.getElementById("tc");
if (!tc.checked)
tc.parentNode.className = 'input-error';
else
tc.parentNode.classList.remove('input-error');
}