Pregunta

I have an ul with li inside. So I use $.each() to search each id of li.

My problem is, I've an id that's "Nouvelle AC". But when I use $(product).indexOf("NOUVELLE"); It returns -1.

To figure out it and turn more easy to understand, I created an jsFiddle.
Use console to understand what I said.

The HTML:

<ul class="product-list">
    <li class="product" id="Me too AC"></li>
    <li class="product" id="Wish BR"></li>
    <li class="product" id="Nouvelle AC"></li>
    <li class="product" id="Gloss Pearl AC"></li>
    <li class="product" id="Gloss Pearl BR"></li>
    <li class="product" id="Kish too AC"></li>
    <li class="product" id="Kit Wish BR"></li>
    <li class="product" id="Fresh AC"></li>
</ul>

The JS:

$('ul.product-list li.product').each(function() {
    var product = "NOUVELLE";
    var produtoloaded = $(this).attr('id');
    console.log('Product loaded: '+produtoloaded);
    console.log('Product searched: '+product);
    console.log('If contains: '+produtoloaded.indexOf(product));

    if (produtoloaded.indexOf(product) > -1) {
        //IF INDEX IS MORE THAN -1 THE STRING CONTAINS THE PRODUCT
        var offsetTop = produtoloaded.offsetTop;
        console.log(offsetTop);
    }
});
¿Fue útil?

Solución

It is a matter of exact search... indexOf function looks for exact string, it is case sensitive:

var product = "NOUVELLE"; //or make in lower case already so that you can skip 'product= product.toLowerCase();'
var produtoloaded = $(this).attr('id');
product = product.toLowerCase();
produtoloaded = produtoloaded.toLowerCase();

console.log('Product loaded: '+produtoloaded);
console.log('Product searched: '+product);
console.log('If contains: '+produtoloaded.indexOf(product));

if (produtoloaded.indexOf(product) > -1) {
    //IF INDEX IS MORE THAN -1 THE STRING CONTAINS THE PRODUCT
    var offsetTop = produtoloaded.offsetTop;
    console.log(offsetTop);
}

You can call in Upper case also, just call toUpperCase() instead of toLowerCase()

Otros consejos

You are looking for uppercase characters in a string which is not.

Add .toUpperCase() and it will work.

produtoloaded.toUpperCase().indexOf(product)

Even better would be to do both strings to upper or lowercase, this will prevent typo's messing up the logic.

produtoloaded.toUpperCase().indexOf(product.toUpperCase())

indexOf is case sensitivity:

var product = "NOUVELLE";
var produtoloaded = $(this).attr('id');
product = product.toLowerCase();
produtoloaded = produtoloaded.toLowerCase();

MDN Doc : .toLowerCase()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top