jQuery contains doesn't work on Chrome

10,560

Solution 1

Use indexOf instead of contains

 if($(this).val().indexOf("cm") == -1) {
    $(this).val(text + " cm");
 }

Solution 2

.contains() checks to see if a DOM element is a descendant of another DOM element hence you should use it with jquery Objects:

Here you can use indexOf() function to check the contents of value attribute.

if($(this).val().indexOf("cm")>=0) {

}

You can refer .contains() for more info.

Solution 3

You could use test:

if(!/cm/.test($(this).val())) {
    $(this).val(text + " cm");
}

Solution 4

There is no such method as contains in Chrome. Instead, you should better use indexOf:

// Instead of...
if ($(this).val().contains('cm')) { /* val() contains 'cm' */ }
// ...do this:
if ($(this).val().indexOf != -1) { /* val() contains 'cm' */ }

Please note that indexOf returns -1 if occurence is not found in string and >= 0 if occurence is found.

Share:
10,560
Aram Mkrtchyan
Author by

Aram Mkrtchyan

My name is Aram Mkrtchyan. I have worked as a front-end developer since 2010. My professional experience includes web projects that were developed by myself and as part of a team. I also have some experience in the development of parallax, responsive and mobile websites. My preferred languages are: xHtml, JavaScript, CSS 3, HTML 5, also I'm started work as Wordpress developer. I am a hard working and motivated person. Besides coding my hobbies are: watching movies, playing strategy games, listening to music (mainly rock), drinking coffee :) http://aramdev.website

Updated on July 23, 2022

Comments

  • Aram Mkrtchyan
    Aram Mkrtchyan almost 2 years

    I have one problem with jquery contains. It work perfect on firefox.

    This is my code.

    $("input[data-height='cm']").blur(function(){
        var text = $(this).val();
    
        if($(this).val().length > 0) {
            if(!$(this).val().contains("cm")) {
                $(this).val(text + " cm");
            }
        }
    });
    

    on chrome it give error

    Uncaught TypeError: $(...).val(...).contains is not a function

    How can I fix it please help.

    Thank you.