DarV DarV - 1 year ago 134
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">

var arrayObjects = <?php echo $json_array; ?>;

var data_id = $(this).data('id');

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

From my console:

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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download