How to retrieve the value of several dropdownlist (only filled in)

2

How can I retrieve the value of several dropdowns (only those filled in)

The function below does not work correctly. For example, if I select only the second combo has output: , 2 He takes the void as if it were a selection. Can you work around this?

    $("div.container-fluid").on("change", "select.dropDown", function() {

 var selectData = [];

        $('select.dropDown option:selected').each(function(i, selected){
            var selectData[i] = $(selected).val();

        });
});

My html looks like this:

<select class="dropDown" id="column_1">
                 <option value="" selected="" disabled="">Please select</option>
                            <option value="1">A</option>
                            <option value="2">B</option>
                            <option value="3">C</option>
                            <option value="4">D</option>
</select>

<select class="dropDown" id="column_2">
                 <option value="" selected="" disabled="">Please select</option>
                            <option value="1">A</option>
                            <option value="2">B</option>
                            <option value="3">C</option>
                            <option value="4">D</option>
</select>
    
asked by anonymous 26.09.2015 / 22:23

1 answer

1

I think you want to use .filter() whose function is to reduce an array to the elements that validate a given condition.

Your code could look like this:

$("div.container-fluid").on("change", "select.dropDown", function () {
    var selectedCombos = $('select.dropDown').filter(function () {
        return this.value;
    });
});

And if you want, instead of the element select the value itself in that array then you can use .map() like this:

$("div.container-fluid").on("change", "select.dropDown", function () {
    var selectedValues = $('select.dropDown').filter(function () {
        return this.value;
    }).map(function(){
        return this.value;
    }).get();
});

jsFiddle: link

It's curious, and perhaps confusing, that both methods have return this.value; . In the first case it checks if the value exists, if it does not remove the element from the array. In the second case ( .map() ) the value that return gives is what is substituted in the array.

    
26.09.2015 / 22:28