2016-04-18 60 views
0

我有这个简单的HTML结构:如何检查多个选择是否被选中?

<div id="kurir_list"> 
    <div class="row"> 
     <div class="col-sm-6"> 
       <select disabled class="tarif"> 
       ... 
       </select> 
      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-sm-6"> 
       <select disabled class="tarif"> 
       ... 
       </select> 
      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-sm-6"> 
       <select disabled class="tarif"> 
       ... 
       </select> 
      </div> 
     </div> 
    </div> 
</div> 

,我有这个jQuery太:

$(".tarif").change(function() { 
    if (!$(".tarif").is(':disabled')) { 
     alert ("hello world"); 

     if ($(".tarif").val() !== "") { 
      alert ("hello earth"); 
     } 
    } 
}); 

为什么“你好地球”一直没有出现,即使所有.tarif已选定的选项?如何验证.tarif是否有空的选择?谢谢

回答

1

您可以使用.filter()方法与length属性。

//Cache elements 
var tarif = $(".tarif"); 

tarif.change(function() { 
    //Filter not disabled elements 
    var notDisabledTarif = tarif.filter('not(:disabled)'); 

    //There is atleast 1 element which is not disabled 
    if(notDisabledTarif.length){ 
     alert ("hello world"); 

     //Filter elements having value 
     var elementHavingValue = notDisabledTarif.filter(function(){ 
      return $(this).val() !== ""; 
     }); 

     if (elementHavingValue.length) { 
      alert ("hello earth"); 
     } 
    } 
}); 
+0

兄弟,问题是,我需要检查所有'.tarif'是否禁用或空值,每次'.tarif'之一改变。不只是目前的选择。但'#kurir_list'下所有选择的元素# –

+0

@RobertHanson,只是澄清,你需要检查任何选择元素有价值,而不是禁用,对不对? – Satpal

+0

是的,这是正确的 –

相关问题