Robert Hanson Robert Hanson - 7 months ago 6
Javascript Question

How To Check Multiple Select Whether It's Selected Or Not?

I have this simplified HTML structure :

<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>


and I have this jquery too :

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

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


why "hello earth" never shows up even though all
.tarif
has selected option? how to make validation whether
.tarif
has empty selection or not? thank you

Answer

See inline comments

//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");
        }
    }
});