The indexOf () function always returns zero even having the same string

advertisements

I have a variable in javascript

var hidden = "class_code,other";

then I have ajax which returning value

$.ajax({
type: "post",
data: $("#myform").serialize,
success: function(data){
    if(hidden.indexOf(data)){
    //mycode here
 }
}
});

but it doesn't work, so I try to use alert() to print the hidden.indexOf(data) and it always returns 0, so I try to alert the data and it's returning "class_code".

Why my script doesn't work even the hidden var is contains the data?


indexOf returns the position where the matching string begins. Since class_code is at the beginning of class_code,other, this is 0. When the string isn't found, it returns -1. The correct way to test if the string is found is with:

if (hidden.indexOf(data) != -1)