jshock
jshock

Reputation: 1503

Javascript if else with jQuery

I am trying to determine if an image source contains a string when I click on the image. The images have the class .swap-color. I have the variable $current_swatch set to the image src attribute, and it tests successfully. My code is below. No matter what image I click on, I get the alert "Contains TB", even if TB isn't in the image src. What am I doing wrong?

<img src="/images/Swatch-TB.jpg" class="swap-color"/>

$("document").ready(function () {
    $('.swap-color').click(function () {
        //get the image src
        var $current_swatch = $(this).attr('src');
        //check if TB is in the src
        if ($('$current_swatch:contains("TB")').length > 0 ) {
            alert ('Contains TB');
        } else {
            alert ('Does not contain TB');
        }
    });
});

Upvotes: 0

Views: 84

Answers (2)

random_user_name
random_user_name

Reputation: 26150

There's enough feedback that I'm going to go out on a limb and post an answer, even though the key to your question could be done in a comment.

The way to check for the contents is to use the JS native indexOf(), rather than the jQuery selector method in your code.

Here's some commented revisions to your code:

// Streamlined, conflict-safe document ready
jQuery(function ($) {
    $('.swap-color').click(function() {
        //get the image src
        var $current_swatch = $(this).attr('src');
        //check if TB is in the src
        // Use JS native "indexOf" rather than jQuery 
        if ($current_swatch.indexOf('TB') > -1 ) {
            alert ('Contains TB');
        } else {
            alert ('Does not contain TB');
        }
    });
});

For more information on different ways to check for a substring, check out this answer: Fastest way to check a string contain another substring in Javascript?

Upvotes: 4

Matthew Herbst
Matthew Herbst

Reputation: 31963

So, you're using the jQuery's contains method which checks if a selector contains a value. The problem is, $current_swatch is actually a string, since $(this).attr('src') will give "/images/Swatch-TB.jpg".

Instead what you want is the vanilla JS includes.

if ($current_swatch.includes('TB')) {
  ...

Upvotes: 1

Related Questions