Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find select option by text

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.

like image 880
CMR Avatar asked Aug 14 '12 10:08

CMR


2 Answers

try this

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

});
like image 119
rajesh kakawat Avatar answered Oct 29 '22 05:10

rajesh kakawat


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

like image 28
undefined Avatar answered Oct 29 '22 05:10

undefined