TheRealPapa TheRealPapa - 1 year ago 151
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

Answer Source

["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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download