选择选项、复选框和单选按钮标签,如果它们为空怎么办?

3

对于文本框和数字,如果它们为空,我们可以轻松发送以下错误命令:

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 optioncheckboxradio标签,如果它们是空的,我应该怎么做?


1
您可以在下拉菜单中使用 :selected 属性,在复选框和单选框中使用 :checked 属性。 - madalinivascu
2个回答

1
您可以像这样使用:

您可以使用类似这样的东西:

$(document).ready(function(){
$('#mySelectBox').each(function() {
 if($(this).val() == -1)     
        $(this).addClass('input-error');     
 else
        $(this).removeClass('input-error');
});

一个fiddle示例在这里。为了澄清一点,我假设您会有一个值为-1的“请选择选项”(因此实际上没有选择任何内容):

});


1
要验证下拉框中的选项是否被选择,您可以检查 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');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接