Panagiotis Koursaris
Panagiotis Koursaris

Reputation: 4023

Multiple select elements - Handle with jQuery when select an option from all of them

I have two select elements with some options. What I want to do is to handle this with jquery so as I can get the values of them only when options have values.

 <div class="panel-heading">
        <select id="loading-by-tag">
            <option value="" disabled selected> -- Select Subject --</option>
            <option value="value1">Selection 1</option>
            <option value="value2">Selection 2</option>
        </select>

        <select id="loading-by-sub-tag">
            <option value="" disabled selected> -- Select Subject --</option>
            <option value="value1">Selection 1</option>
            <option value="value2">Selection 2</option>
        </select>
    </div>

If I want to handle with one select element only I use .on('change', function() with select element and it works, but with multiple select element how can I do it.

Upvotes: 0

Views: 70

Answers (2)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Just a side note, use .filter() :

$('select').change(function() {
  var m = $(this).siblings('select').addBack();
  var n = m.filter(function(){
    return $(this).val() == null && $(this)
  });  
 if ( !n.length ) alert('both selected')
});

DEMO

Upvotes: 1

Adam
Adam

Reputation: 5233

You should check if selectedIndex is not 0 for all your select elements.

$(document).on('change', 'select', function () {
    var allChanged = true;


    // check if there is any other select element which was not changed
    $('select').each(function () {
        if (this.selectedIndex == 0) {
            allChanged = false;
        }
    });

    // if all select elements have been changed
    if (allChanged) {
        alert('BOTH CHANGED');
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-heading">
        <select id="loading-by-tag">
            <option value="" disabled selected> -- Select Subject --</option>
            <option value="value1">Selection 1</option>
            <option value="value2">Selection 2</option>
        </select>

        <select id="loading-by-sub-tag">
            <option value="" disabled selected> -- Select Subject --</option>
            <option value="value1">Selection 1</option>
            <option value="value2">Selection 2</option>
        </select>
    </div>

Upvotes: 3

Related Questions