Graham Graham - 3 months ago 8
HTML Question

How to select all dropdowns that have a specific value selected?

I don't know if this is possible, but is there a succinct way of selecting all drop downs on a page that have a specific value selected.

For example, I have a number of identical dropdowns (except the id) like so:

<select class="whatever">
<option value="1">one</option>
<option value="2">too</option>
<option value="3">fwee</option>
</select>


I want to be able to do something like this:

$(".whatever:2")


where it would select only those dropdowns that have option with value of 2 selected

All relevant code:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function go()
{
alert($(".whatever input[value='2']").length);
}
</script>
<select class="whatever" id="a">
<option value="1">one</option>
<option value="2">too</option>
<option value="3">fwee</option>
</select>
<select class="whatever" id="b">
<option value="1">one</option>
<option value="2">too</option>
<option value="3">fwee</option>
</select>
<select class="whatever" id="c">
<option value="1">one</option>
<option value="2">too</option>
<option value="3">fwee</option>
</select>
<input type="button" onclick="go();" value="go" />

DVM DVM
Answer

I think this should cover what you need:

$(document).ready(function() {
    jQuery("#btn").on('click',function(){
  $('select').filter(function() {
            return $(this).val()==='2';
  }).each(function(){
  console.log($(this).attr("id"))
  })   
    });

});

http://jsfiddle.net/kMb3p/

I've added the console.log there so you can see that it returns the id of the right select elements. That can be changed depending on what you need to do with it :)