简体   繁体   中英

jquery set selected attribute on an option using like

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');

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;
    };
}); 

Fiddle Demo

Try,

$('#image_id').find('option:contains("Ubuntu -12.04")').prop('selected',true);

Working Demo

So as per your new request you can do like,

$('#image_id').find('option:contains("Ubuntu"):contains("-12.04")').prop('selected',true);

Working Demo

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();
});

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM