Víctor Bonilla
Víctor Bonilla

Reputation: 51

javascript variable inside indexOf

I am trying to reuse a function and I am defining a variable that is breaking the function when trying to put it inside of indexOf(). I've tried several approximations but I can't figure out why it's not working. The code is like this:

function toggleSelectAll(control, nadaValue) {
var allOptionIsSelected = (control.val() || []).indexOf('"' + nadaValue + '"') > -1;

In the case the function is breaking, toggleSelectAll is called like this:

toggleSelectAll($(this), 1);

trying to subsitute this one:

function toggleSelectAll(control) {
var allOptionIsSelected = (control.val() || []).indexOf("1") > -1;

You can see a couple of JSFiddle examples to illustrate better:

This works: http://jsfiddle.net/victorRGS/o8cjtoqp/1/

This doesn't: http://jsfiddle.net/victorRGS/o8cjtoqp/2/

If you can throw some light on this it would be great! Thanks in Advance!

Upvotes: 1

Views: 5796

Answers (2)

Teemu
Teemu

Reputation: 23406

indexOf uses strict comparison when cheking the argument could be found from an array.

The data you have is type of string. However, you're passing a number as nadaValue, hence indexOf always fails to find a match from the array.

To fix this, you've either to pass a string as nadaValue, or explicitly convert it to a string before use in indexOf. A handy way would be to create a temporary string:

(... indexOf(nadaValue.toString()) ... )

This way you can preserve the number type, if it is needed later in the code.

Upvotes: 1

Abhijeet
Abhijeet

Reputation: 4309

There is problem with your code. indexOf() function uses strict comparison i.e. comparing with '===' which will compare data and datatype. So while comparing nadaValue it (indexOf()) is checking for literal 1 instead of String 1 i.e. "1".

Upvotes: 0

Related Questions