TheRealPapa TheRealPapa - 1 month ago 17
jQuery Question

Convert string to array - jQuery.inArray() not working

I have a string that looks like this (this is a value I get from an input in the page's HTML):


I turn this value into an array in my JS:

var tempProjectTasks = $('#task_id_array').val();
tempProjectTasks = tempProjectTasks.replace('[', '').replace(']','');
selectedProjectTasks = tempProjectTasks.split(',');

I then compare this array in a loop

$.each(tasks, function(key, value) {
if ($.inArray(value['id'], selectedProjectTasks) != -1) {
checked = 'checked';
} else {
checked = '';
... more stuff here ...

This is building a list for the HTML and each row contains a checkbox.

I can see in the console the comparison for these values being
by adding the
commands below inside the loop.

console.log($.inArray(value['id'], selectedProjectTasks));

In the console:


Why is the
not finding the matching values? What have I missed? Thanks


["123","234","345"] is an array of string, where as 123 is an integer.

You can convert this to string using toString before searching it in array

console.log($.inArray((value['id'].toString(), selectedProjectTasks));