Quantcast
Viewing latest article 1
Browse Latest Browse All 3

How to See if String Contains Substring jQuery

I have a shoppingcart that displays product options in a dropdown menu, and I want to make some other fields on the page only visible if they select “Yes” in the previous option. The problem is that the shopping cart also includes the price modifier in the text, and that can be different for each product. So if I do this it works:

 $(document).ready(function() {
  $('select[id="Engraving"]').change(function() {
   var str = $('select[id="Engraving"] option:selected').text(); 
   if (str == "Yes (+ $6.95)") {
    $('.engraving').show();
   } else {
    $('.engraving').hide();
   }
  });
 });

However I would rather use something like this:

 $(document).ready(function() {
  $('select[id="Engraving"]').change(function() {
   var str = $('select[id="Engraving"] option:selected').text(); 
   if (str *= "Yes") {
    $('.engraving').show();
   } else {
    $('.engraving').hide();
   }
  });
 });

Which doesn’t work.

I only want to perform the action if the selected option contains the word “Yes”, and would ignore the price modifier.

I appreciate any help.

Solution

Like this:

if (str.indexOf("Yes") >= 0)

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

The post How to See if String Contains Substring jQuery appeared first on Solved.


Viewing latest article 1
Browse Latest Browse All 3

Trending Articles