10

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
CMR
  • 1,366
  • 4
  • 15
  • 31

3 Answers3

15

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

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Hi, see my comment on the other one who suggested contains – CMR Aug 14 '12 at 10:45
  • Hmm, just tried that but doesn't seem to work either. Not getting any console errors though. EDIT: got it working now, had to change "input" to "option" thanks. – CMR Aug 14 '12 at 10:54
2

You will probably have more luck with this:

$('.assUnit').find('option:contains('+unitName+')').remove();

See also: :contains() selector

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Hi, contains isn't any good for this, as it has to be an exact match. contains('unit2') for example would also match 'unit200' and there will be a lot of select menus and options. – CMR Aug 14 '12 at 10:44
1

try this

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

});
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40