Javascript 选择选项、复选框、无线电标签(如果为空)

Javascript 选择选项、复选框、无线电标签(如果为空),javascript,jquery,html,Javascript,Jquery,Html,对于文本框和数字,如果它们为空,我们将非常轻松地发送以下错误命令: 阿贾克斯 CSS 但是对于选择选项,复选框,收音机标签,如果它们是空的,我该怎么办?您可以使用类似的方法: $(document).ready(function(){ $('#mySelectBox').each(function() { if($(this).val() == -1) $(this).addClass('input-error'); else $(this

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

阿贾克斯

CSS


但是对于
选择选项
复选框
收音机
标签,如果它们是空的,我该怎么办?

您可以使用类似的方法:

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


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

要验证是否选择了组合框项目,可以检查selectedIndex值。 通过复选框,可以检查其checked属性

工作示例位于


您有用于选择的
:selected
属性和复选框/收音机的
:checked
属性
.input-error {
    border-color: red;
}
$(document).ready(function(){
$('#mySelectBox').each(function() {
 if($(this).val() == -1)     
        $(this).addClass('input-error');     
 else
        $(this).removeClass('input-error');
});
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');
}