سؤال

Simply put, using this:

<select id="Test">
    <option value="1">ABC</option>
    <option value="2">DEF</option>
</select>

How can I use jQuery to get option[value="2"] using only "DEF" - Keep in mind I am using 1.8.2

Thank you!

هل كانت مفيدة؟

المحلول

Try the :contains() selector:

$('#Test option:contains("DEF")')

Fiddle

Note that :contains() is a wildcard search. If you need an exact match, I think you'll just need to iterate or filter the options and check the text(). Here's one possibility:

http://jsfiddle.net/YuK2K/

console.log(getOptionByText('Test', 'DEF'));

function getOptionByText(id, value) {
    return $('#' + id).find('option').filter(function() {
       return $(this).text() == value; 
    });
}

نصائح أخرى

You can use contains if you are sure that no other option that appears prior contains that value. Note that contains does a wildcard match not an exact match. Instead you can do this way to do an exact match.

$('#Test option').filter(function () {
    return this.innerHTML === 'DEF'
}).val();

Fiddle

Does it help?

$( '#Test option' ).each( function() {
    if ( $( this ).html() == 'DEF' ) {
        alert( $( this ).val() );
    }
} );
$("select option:contains('ABC')")

here is example - http://jsfiddle.net/maximua/7fF7M/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top