This question already has an answer here:
I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code 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, which doesn't work:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.
It's pretty late to write this answer, but I thought of including it anyhow.
String.prototype
now has a methodincludes
which can check for substring. This method is case sensitive.To check for a substring, the following approach can be taken:
Check out the documentation to know more.
You can use this Polyfill in ie and chrome
you can define an extension method and use it later.
so that you can use in your page anywhere like:
which returns true.
Refer below post for more extension helper methods. Javascript helper methods
You can also check if the exact word is contained in a string. E.g.:
Usage:
This is how jQuery does its hasClass method.
None of the above worked for me as there were blank spaces but this is what I did
I know that best way is
str.indexOf(s) !== -1;
http://hayageek.com/javascript-string-contains/I suggest another way(
str.replace(s1, "") !== str
):