Ignore data type checking when using $ .inArray

1

I'm having the following problem with jQuery : When I try to check an existing value inside an array, with the $.inArray method, it is returning an unexpected result.

Example: I want to check if 1232 exists within Array , which is returned by the $.map function. As follows:

HTML

<div class="elemento" data-nome="teste"></div>
<div class="elemento" data-nome="1232"></div>

Excerpt from the jQuery code

var value = $('.input').val();

var definedNames = $('.pai').find('.elemento').map(function(){

    return $(this).data('nome');

}).toArray();

if ($.inArray(value, definedNames) !== -1 || !value.length) {

    return false;
}
What is happening is that within map , the return of data('nome') (in case of value 1232) is of type Number ; however, when it comes from $('.input').val() , it comes as String

In PHP there is a way to check for the in_array function, if the values are also of the same type.

Example:

in_array(1, ['1']) // true
in_array(1, ['1'], true) // false

In jQuery, is there any way to specify that I want to find the same value in the array, but ignoring the type check? Or will I always have to convert the number to String ?

    
asked by anonymous 09.02.2015 / 18:38

1 answer

1

What should be converting string value to Number is .data , which is a jQuery function that confuses people a little. It was not done simply to read / write values from the data-attributes, but rather to associate arbitrary data with DOM elements (without hanging them directly on the elements, jQuery creates a dictionary internally).

So, I think changing the way you create the array would be enough:

var definedNames = $('.pai').find('.elemento').map(function(){
    return $(this).attr('data-nome');
}).toArray();

This will mount an array with the original value of the data-nome attribute of each element, and attribute values are always strings.

    
09.02.2015 / 18:46