如何检查多个选择是否选择?

时间:2016-04-18 15:10:32

标签: jquery

我有这种简化的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");
        }
    }
});

为什么&#34;你好地球&#34;即使所有.tarif都选择了选项,也从不显示?如何验证.tarif是否有空选择?谢谢

1 个答案:

答案 0 :(得分: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");
        }
    }
});