0

I have been using the following code to add some extra text onto a dropdown option:

jQuery("[id='product option1'] > option:contains('Notebook')").text('Notebook - OUT OF STOCK');

I have to get the option by it's Text as 1000's of my products use this same dropdown and they each have their own different value. It is just the text that is the same for all.

This works but also in my dropdown list is Notebook Large so using the above adds - OUT OF STOCK to any options with the words Notebook.

I know this is because I am looking for contains. What can I use to find the option with the exact text only?

note: I know it is not best practice but I cannot change the id to not have spaces hence the need for [id='product option1'] as the selector.

odd_duck
  • 3,941
  • 7
  • 43
  • 85
  • leave your data sample would help too much. And please mention your jquery version some version has some bugs. – MSS Sep 15 '16 at 15:44
  • 3
    Possible duplicate of [jquery : How to select an option by its text?](http://stackoverflow.com/questions/3744289/jquery-how-to-select-an-option-by-its-text) – Jamie Barker Sep 15 '16 at 15:45
  • yes filter also works – MSS Sep 15 '16 at 15:47

3 Answers3

0

Try this:

jQuery("[id='product option1']")
.children()
.filter(function(i,v){return v.innerText.indexOf('Notebook')>-1;})
.text('Notebook - OUT OF STOCK');
MSS
  • 3,520
  • 24
  • 29
0

I usually used filter, which takes a function as a parameter and if is true it is added to the stack, otherwise it is skipped, so in this case it should look something like:

jQuery("*[id='product option1']")
    .find('option')
    .filter(function (){
          return $.trim($(this).text())=='Notebook';
    })
    .text('Notebook - OUT OF STOCK');
peterpeterson
  • 1,315
  • 2
  • 14
  • 38
0

None of the answers worked for me as they still gave me all options which contained that text. The link given to me by @Jamie Barker:

jquery : How to select an option by its text?

Gave me the correct result (thanks to Dr. C. Hilarius)

Code is:

jQuery("[id='product option1'] > option:contains('Notebook')").each(function(){
    if (jQuery(this).text() == 'Notebook') {
        jQuery(this).text('Notebook - OUT OF STOCK');
        return;
    }
});
Community
  • 1
  • 1
odd_duck
  • 3,941
  • 7
  • 43
  • 85