JQuery/Javascript检查下拉列表

JQuery/Javascript checking dropdown list

本文关键字:下拉列表 检查 Javascript JQuery      更新时间:2023-09-26

我正在开发一个web应用程序,在一个页面中有两个下拉列表。

<div id="A">
<select>
    <option value="">please select</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
<select>
    <option value="">please select</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
</select>
</div>

现在,我想让两个下拉列表都必须选择(除了"请选择"),否则用户无法继续。这是我的jquery代码。

        var error=0;
        var selected_option = $('#A>select option:selected');
        $('#A').each(function() {
            if(!$('#A select').selected){
                error++;
            }
        });
        if (error>0) {
            alert('Choose the bloody option');
            return false;
        }

到目前为止,实际结果是警报消息运行良好,强制选择部分工作良好。然而,即使我从两者中选择,我仍然保持警惕并陷入困境。我想可能是我的if condition设置不正确。求你了,有人帮我。非常感谢。

更改val()的selected以获得select的值。

 if(!$('#A select').val()){

你可以在这里尝试这个是实现你想要的的另一种方法

$('#A select').each(function() {
   if(this.options[this.selectedIndex].value != 'please select'){
       //do here your action
   }
}

DEMO

 var selected_option = $('#A>select option:selected');
 $('#check').click(function () {
     var error = 0;
     $('#A select').each(function () {
         if ($(this).val() == '') {
             error++;
         }
     });
     if (error > 0) {
         alert('Choose the bloody option');
         return false;
     }
 });

你能试试吗:

var errors = 0;
$("#A select").each(function(){
if($(this).find("option:selected").is(":eq(0)")){
        errors++;
}
});
if(errors>0){ alert('error!'); }

尝试

var valid = $('#A select').filter(function(){
    return $.trim($(this).val()) == ''
}).length == 0
if(!valid){
    alert('not selected')
}

演示:Fiddle

另一个版本

if ($('#A select').has('option:selected[value=""]').length > 0) {
    console.error('not selected')
}else {
    console.log('valid')
}

演示:Fiddle

试试这个:

  $('#A select').each(function() {
      if($(this).find('option:selected').text() == 'please select'){
         error++;
      }
  });