find select option by text

CMR picture CMR · Aug 14, 2012 · Viewed 14.9k times · Source

Can anyone tell me why this works in older versions of jQuery (e.g. 1.4.2) but if you switch to a later version, e.g. (1.6 +) it stops working?

http://jsfiddle.net/nmvf6/1194/

$(function(){
    $('#my_button').click(function(){
        var unitName = "Unit2";
        $('.assUnit').find('option[text="'+unitName+'"]').remove();
    });

});

I have checked the error output in the console for the later versions, and an error seems to occur on the page load, before i've even got as far as it loading up my script and being able to click the button..

When I change the version to 1.8.0 for example and Run the page, this error comes up in my Opera scripts console:

Which seems to be in a "mootools" file..but I didn't select mootools, i selected jQuery 1.8.0

:/

Thanks.

Answer

undefined picture undefined · Aug 14, 2012

You are using Attribute Equals selector which selects elements that have the specified attribute with a value exactly equal to a certain value, option elements don't have text attributes, you can use :contains selector instead, try this:

Select all elements that contain the specified text.

$(function(){
    $('#my_button').click(function(){
        var unitName = "Unit2";
        $('.assUnit').find('option:contains('+unitName+')').remove();
    });
});

FIDDLE

If you want to select the element that has only certain value you can use the filter method:

$(function(){
    $('#my_button').click(function(){
        var unitName = "Unit2";
        $('.assUnit option').filter(function() {
             return $(this).text() === unitName
        }).remove();
    });
});

FIDDLE