jQuery - remove select option based on text not value

27,432

Solution 1

you can use :contains to filter based on text content of an element, but note that it will return partial matches. So :contains('Vaillant 835') will return :contains('Vaillant 835') and :contains('Vaillant 8356')

jQuery("#select_Boiler option:contains('Vaillant 835')").remove();

If you want to filter for equal you need to do a manual filter like

jQuery("#select_Boiler option").filter(function(){
    return $.trim($(this).text()) ==  'Vaillant 835'
}).remove();

Solution 2

Here's the case insensitive option of Arun P Johny's answer.

jQuery("#select_Boiler option").filter(function() {
    cur_text = $(this).text().trim().toLowerCase();
    return cur_text.indexOf('Vaillant 835') != -1;
}).remove();
Share:
27,432
odd_duck
Author by

odd_duck

Updated on January 30, 2020

Comments

  • odd_duck
    odd_duck over 4 years

    I have a dropdown box as follows:

    <select id="select_Boiler">
      <option value="boiler_1645">Vaillant 831</option>
      <option value="boiler_2373">Worcester 24</option>
      <option value="boiler_3009">Vaillant 835</option>
      <option value="boiler_4354">Bosch 671</option>
    </select>
    

    I need to be able remove specific options using jQuery but based on the text not the option value. I've tried this without success:

    jQuery("#select_Boiler option[text='Vaillant 835']").remove();
    

    I know I can do the same with value as below and it works but i need to do it by text

    jQuery("#select_Boiler option[value='boiler_3009']").remove();
    
  • Ravi Wadje
    Ravi Wadje about 6 years
    It is not working for IE11, can you please help me out.