Skip to content
Fix Code Error

How do I check if string contains substring?

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

Like this:

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

…or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn’t found at all.

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))
Answered By: Anonymous

Related Articles

  • Form field border-radius is not working only on the…
  • Trouble with boxes appearing/hiding based on selection
  • How can I pass a wct test while rearranging children…
  • When I use '/js/app.js' on my Laravel view my…
  • Generating a drop down list of timezones with PHP
  • FillMaxHeight, padding and wrapping content not…
  • Having trouble with my nav bar/header, It used to…
  • How to transfer browser’s session state across pages?
  • React Multi-level push menu SCSS Back button not working
  • Trying to keep dropdown menus flush to the edge of…
  • How to implement a Navbar Dropdown Hover in Bootstrap v4?
  • Polymer - How to data-bind paper-dropdown menu…
  • How to reuse function with parameters in Vue…
  • How do you sort table columns with Vue.js?
  • Bootstrap 4: Multilevel Dropdown Inside Navigation
  • Use of Jquery on scroll event
  • Polymer paper-dropdown-menu not rendered correctly…
  • How to set `border-radius` of `paper-listbox` inside…
  • How to reset a prop value to it's original value in Vuejs
  • Polymer 1.x: Observers
  • Scrollable Menu with Bootstrap - Menu expanding its…
  • Get selected item and its count
  • Hide one dropdown in side menu when another opens
  • How to update other fields based on a field value in…
  • How to sum up values working with c# and Newtonsoft JSON?
  • Polymer 1.0 dynamically add options to menu
  • Ember 2, filter relationship models (hasMany,…
  • Vue price range filter
  • (Next/react) SWR refresh from button click in child…
  • Prevent menu close on multi select…
  • polymer event not fired
  • How to make Twitter Bootstrap menu dropdown on hover…
  • Bootstrap dropdown sub menu missing
  • Adding Google Translate to a web site
  • Polymer 1.x: Two-way databinding for paper-dropdown-menu
  • req.session.cart [object object] [object object] how…
  • How to show multiple select options when user select…
  • How can I handle paper-dropdown-close event in my…
  • Replace/Update The Existing Array of Object that…
  • in responsive menu it puts two links on the same line
  • After a little scroll, the sticky navbar just is not…
  • paper-dropdown-menu default selected option doesn't work
  • Navbar not filling width of page when reduced to mobile view
  • Smart way to truncate long strings
  • How to filter a model Django and compare against an id
  • paper-item - way to place value for paper-dropdown?
  • Unset WooCommerce checkout fields based on cart…
  • How to get data value from bookstrap dropdown-menu…
  • Reference - What does this regex mean?
  • How do I enable dropdown on hover in vue bootstrap?
  • hide select options using only css
  • Getting a "TypeError" when trying to validate a form
  • Update nested object in array in ReactJs
  • How to re-render a component from another component…
  • Polymer example not working on Firefox
  • ContentScale.FillWidth is not working Jetpack Compose
  • Ember.js + HTML5 drag and drop shopping cart demo
  • Typeerror: n is undefined in underscore.min.js
  • How to dynamically add and remove views with Ember.js
  • Vue.js - Element UI - Nested dialog won't open from…
  • How does String substring work in Swift
  • Any quick way of updating a column based on timestamp
  • How to keep disappearing Flutter Bottom Navigation…
  • How to style Polymer dropdown menu arrow
  • Add a Polymer paper-dropdown-menu to a page from javascript?
  • Vuex and reactivity in list rendering
  • In Jquery show selected a value from the searched…
  • What are the undocumented features and limitations…
  • bootstrap-vue multi level drop down
  • Set selected value in a paper-menu in Polymer 1.0
  • jQuery Mobile: document ready vs. page events
  • sql query to find priority jobs
  • Pandas: convert column (price data) to integer
  • Avoid dropdown menu close on click inside
  • Bootstrap: Position of dropdown menu relative to navbar item
  • ngModel Binding on Polymer dropdown (Angular2)
  • I don't know why this python code for replacing all…
  • How can I remove data from the page and it doesn't show?
  • paper-dropdown-menu not working in a lit-element
  • Automatic basket cleaning and quantity update -…
  • Uncaught TypeError exports is read-only
  • Pass values from Element UI autocomplete in the…
  • How to use Servlets and Ajax?
  • Polymer 1.x: Databinding Arrays
  • Align nav-items to right side in bootstrap-4
  • Can't fire iron-select event on paper-listbox
  • polymer 1.0 dom-repeat filter only runs once
  • How do I put the selected core-menu item into a…
  • Binding polymer paper-dropdown-menu to localstorage
  • Aurelia is emitting different css code in Foundation…
  • How can I find the product GUID of an installed MSI setup?
  • Localstorage with React States
  • How to instantiate route in a Polymer app located on…
  • Cart bulk quantity discount for specific product tag…
  • Increase bootstrap dropdown menu width
  • Multiple context menu in a single qTableView pyqt5
  • Dropdown menu cutting off
  • How to use Bootstrap-Vue with a custom navbar…
  • Svelte way for obtaining props values -in parent…
  • vue.js 2.0 communication best practice

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do you append to a file?

Next Post:

Get key by value in dictionary

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error