FLX
FLX

Reputation: 2679

Get select element by selected value

I'm looking for a way to get a select element using it's selected value. It's easy for options : $('option[value="lol"]');

But it's not working with $('select[value="lol"]');

Is it possible to do this with a simple selector ?

Upvotes: 1

Views: 78

Answers (2)

wahwahwah
wahwahwah

Reputation: 3177

You could use something like this in jQuery:

var lol = getSelect(1);

lol.css({
  "color": "red"
});


function getSelect(i) {
  var option = $('select option[value="' + i + '"]');
  return option.parent('select');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="myselect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

You could use a filter?

$("select").filter(function() {
    return $(this).val() === "lol";
});

jsFiddle Example

This is assuming you want all <select> elements where the lol option is actually selected. If you just wanted to check to see if the select contains the lol option, selected or not, you can use parent:

$('option[value="lol"]').parent();

jsFiddle Example

Upvotes: 1

Related Questions