Reputation: 85
I want to call the function loadInWhat using an onclick and populate my input id="what" using the value of LI
function createDivBox(data){
document.getElementById("whatContainer").style.display="block";
document.getElementById("whatContainer").classList.add("ac-container");
var node = "";
for (var i=0; i<data.Suggestions[0].Results.length;i++)
{
var textnode ='<li value="'+data.Suggestions[0].Results[i].Name+'" onclick="loadInWhat(this.value)">'+data.Suggestions[0].Results[i].Name+'</li>';
node = node.concat(textnode);
}
document.getElementById("whatContainer").innerHTML = '<div class="ac-content"><div class="ac-bd" id="ac-bd"><ul>'+node+'</ul></div></div>';
}
function loadInWhat(loadStr)
{
document.getElementById("what").value=loadStr;
}
My function dynamically created li elements on the basis of the JSON object data.I want that if i click on any li element the input id="what" field gets populated by its value ie data.Suggestion[0].Results[0].Name
Whenever im passing this.value only '0' is passed.
Upvotes: 1
Views: 69
Reputation: 2030
Value for li tag must be an integer. Reference.
I would suggest using data attributes instead.
EDIT: Data attributes example
Create li like this (I am passing the whole element to the javascript function);
var textnode ='<li data-val="'+data.Suggestions[0].Results[i].Name+'" onclick="loadInWhat(this)">'+data.Suggestions[0].Results[i].Name+'</li>';
The you can access this value in Javascript like this;
function loadInWhat(el)
{
var loadStr = el.dataset.val;
document.getElementById("what").value=loadStr;
}
Upvotes: 2