Ignore data type check when using $.inArray

Asked

Viewed 83 times

1

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

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

HTML

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

Excerpt from 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’s happening is that inside the map, the return of data('nome') (in the case of 1232) is of the type Number; but when it comes to $('.input').val(), he comes as String

In PHP there is a way to check by function in_array, 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 I’ll always have to convert the number to String?

1 answer

1


What must be converting the string value to Number is the .data, which is a jQuery function that confuses people a little bit. It was not made simply to read/write values of data-Attributes, and yes to associate arbitrary data to DOM elements (without hanging them directly on the elements, jQuery creates a dictionary internally).

Therefore, I believe that 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 attribute value data-nome of each element, and attribute values are always strings.

  • very good! doesn’t even need the gambiarra of the toString() rsrsrsrsrs

  • Which toString?

  • What I was going to put down if I didn’t find an answer. return $(this).data('nome').toString() within the $.map

  • Ah! I complemented the answer now explaining why you don’t need.

  • 3 minutes to mark as solved :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.