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??

Barney
  • 2,355
  • 3
  • 22
  • 37
Kroll
  • 105
  • 1
  • 10

3 Answers3

1

27 and "27" are different.

Try parsing id to integer:

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

OR:

listClients.indexOf(parseInt(id, 10))
0

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

qtgye
  • 3,580
  • 2
  • 15
  • 30
0

cast id to integer by using parseInt() method

Joey Dias
  • 82
  • 4