0

I have a problem with 'indexOf'. When i pass a numerical value in argument, it works, but not with a variable:

$.ajax({
    url: 'bdd.php',
    type: 'POST',
    data: {'jsonNomCommune': jsonNomCommune, 'client': client},
    success: function(data) {
        data = JSON.parse(data);
        listClients= data.clients;
        listProspects = data.prospects;

        $('#tableCSV tbody tr ').each(function(){
            var id = $(this).attr('id');
            id=id.substring(4);

            if (listClients.indexOf(id) > -1){
                $(this).css("background-color","red");

            }

            if (listProspects.indexOf(id) > -1){
                $(this).css("background-color","blue");
            }


        });
    }
});

listProspects and listClients are arrays of numericals values. For example, 27 is in listClients, so when id=27, "listClients.indexOf(id) > -1" should works, but it doesn't. And when i write: "(listClients.indexOf(27) > -1)" it works.

Where is the problem??

4
  • 1
    can you add a console.log(id) right before the indexOf, to check it has the expected value? Commented May 22, 2015 at 10:18
  • 1
    I reckon id might be a string. If so, you can use parseInt(id) to make sure it's an int. Commented May 22, 2015 at 10:20
  • id is a string as substring returns a string! Commented May 22, 2015 at 10:21
  • 3
    @evolutionxbox When using parseInt() you should always pass the radix parameter. Commented May 22, 2015 at 10:21

3 Answers 3

1

27 and "27" are different.

Try parsing id to integer:

listClients.indexOf(+id) //note, its parsing

OR:

listClients.indexOf(parseInt(id, 10))
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't +id turn id into a string? Surely it needs to be an int?
"When using parseInt() you should always pass the radix parameter." Thanks to @Phylogenesis.
@evolutionxbox Unary + always returns a number. This is a common idiom for converting a numeric string to a number.
0

You should cast the value of $(this).attr('id') into a number.
So it should be var id = Number($(this).attr('id'));

Comments

0

cast id to integer by using parseInt() method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.