Buendiadas
Buendiadas

Reputation: 851

Check how many selects have had an options selected using jQuery

I got a bunch of selects:

<select name="paraquien" class="selectpicker form-control paraquien" id="paraquien" onchange="mostrarPreguntas();">
    <option value=""><?=__('¿Para quién es el plan?')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
    <option value="1"><?=__('Para mi')?> <span class="glyphicon glyphicon-triangle-bottom"></span></option>
    <option value="2"><?=__('Para regalar')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
</select> 

and I would like to know if all of them have been selected, and in that case trigger an event. I've tried this far:

jQuery('.paraquien option:selected')

Getting this result array:

[
    <option value=​"1">​Para mi ​</option>​, 
    <option value=​"1">​Hombre​</option>​, 
    <option value=​"3">​Estudiante​</option>​,
    <option value>​Su situación sentimental​</option>​,
    <option value>​¿Tiene hijos?​</option>
​]

You can see every option selected has a value attribute set, what I would like to know is how to get just the options which value has been already set, in the same selector mentioned before.

Any Idea?

Upvotes: 3

Views: 41

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337733

You can use filter() to check for select elements where the value is still ''. Try this:

var $unchosenSelects = $('.paraquien').filter(function() {
    return $(this).val() == '';
});
if ($unchosenSelects.length) {
    // there was at least one select within nothing chosen...
}

Similarly you could use map() to get all the values in an array, then $.inArray to check for empty strings:

var chosenValues = $('.paraquien').map(function() {
    return $(this).val();
});
if ($.inArray(chosenValues, '') != -1) {
    // there was at least one select within nothing chosen...
}

Upvotes: 2

Related Questions