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?
very good! doesn’t even need the gambiarra of the
toString()rsrsrsrsrs– Wallace Maxters
Which
toString?– bfavaretto
What I was going to put down if I didn’t find an answer.
return $(this).data('nome').toString()within the$.map– Wallace Maxters
Ah! I complemented the answer now explaining why you don’t need.
– bfavaretto
3 minutes to mark as solved :)
– Wallace Maxters