Reputation: 46909
How can i set ubuntu selected from the following select box i tried the following below
<select>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
<option value="val3">Ubuntu -12.04 amd......</option>
</select>
$('#image_id').find('option[text="ubuntu"]').attr('selected');
Upvotes: 0
Views: 46
Reputation: 67207
Try,
$('#image_id').find('option:contains("Ubuntu -12.04")').prop('selected',true);
So as per your new request you can do like,
$('#image_id').find('option:contains("Ubuntu"):contains("-12.04")').prop('selected',true);
Upvotes: 1
Reputation: 78525
I like to use .filter to gain more control over the finding process:
// Use the function overload for val
$("#image_id").val(function() {
// Find the value of the option inside which matches the criteria
return $(this).find("option").filter(function() {
var text = $(this).text().toLowerCase();
// Do a case-insensitive search for both "ubuntu" and "12.04"
return text.indexOf("ubuntu") > -1 && text.indexOf("12.04") > -1;
}).val();
});
Upvotes: 0
Reputation: 38102
I assume that your select
has id value as image_id
:
<select id="image_id">
then you can use :contains() selector:
$('#image_id').find('option:contains("Ubuntu")').prop('selected',true);
Note: :contains
is case-sensitive , if you want to match ubuntu
as well than you need to override the default :contains()
method:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Upvotes: 1