User2012384 User2012384 - 4 months ago 26
Javascript Question

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:

$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});


The script was stuck on this line:

prePopulate: populateValue


When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The
populateValue
is:

[{
"id": "11566",
"name": "Smith - White"
}]


There was a javascript error:


Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`


How can I fix this error?

Answer

You need to parse the string in your populateValue variable to an object:

prePopulate: $.parseJSON(populateValue)

Or alternatively, in plain JS:

prePopulate: JSON.parse(populateValue)