How to set an option in select by text using jQuery? The following works
$("#selectID option:contains('optionText')").attr("selected", true);
Is there a simpler/shorter way?
Example
<select id="fruit">
<option value="">--select--</option>
<option value="1">apple</option>
<option value="2">pineapple</option>
<option value="3">orange</option>
<select>
<br>
<button>apple</button>
<button>orange</button>
<button>pineapple</button>
$(function() {
$("button").click(function() {
$("#fruit option:contains('" + $(this).text() + "')").attr("selected", true);
})
})
EDIT
The version posted above using Contains has a bug. Since the Contains would match partial strings also (e.g. apple would match pineapple), it can select incorrect options.
// Doesn't work in FF4, IE9 using jQuery 1.4.4
$('#fruit').val('apple'); // Doesn't work in FF4, IE9 using jQuery 1.4.4
// Doesn't work either in FF4, IE9 using jQuery 1.4.4
$('#fruit option[text="apple"]').attr("selected", true);
// This works
$("#fruit").children("option[text='apple']").attr("selected", true);
EDIT Feb 14th, 2012
// The above doesn't work in jQuery 1.7.1
// Using even more verbose version [Demo][2]
var buttonText = $(this).text();
$("#fruit option:contains('" + buttonText + "')")
.filter(function(i){
return $(this).text() === buttonText;
})
.attr("selected", true)
Demo
EDIT Feb 14th, 2012