DarV DarV - 3 months ago 21
jQuery Question

jQuery - Checking if -data element exist in array with each() and inArray()

my goal is to check if any -data (data-id) on site have same value as one of elements in array but inArray always returns -1

<a href="#" data-id="2">
<a href="#" data-id="3">

<script>
var arrayObjects = <?php echo $json_array; ?>;
console.log(arrayObjects);

$("[data-id]").each(function(){
var data_id = $(this).data('id');

if(jQuery.inArray(data_id, arrayObjects) > -1) { // f
console.log(data_id);
console.log('found');
} else { // nf
console.log(data_id);
console.log('not found');
}
});




From my console:

["2", "3"]
3
not found
2
not found

Answer

When you retrieve the data-id var data_id = $(this).data("id"), you get a Number, whereas the arrayObjects contains Strings !

Here, check this JSfiddle you'll see that the console.log(typeof(data_id)) is Number. To get this work, just add ""+ to force the data_id to be a String :

jQuery.inArray(""+data_id, arrayObjects)