I'm trying to make a remote autosuggest with ajax and am having trouble making an ul with an onclick function. What I receive as the ajax response is simply something like
One Name
Another Name
separated by \n
so below is what I have so far. The problems it has: it's very ugly code, AND the line between /////////////// doesn't work. Apparently it saves a reference to the variable, and all elements fill the text input with the value of the last element.
Can anyone help me fix this? either a way to just pass a copy of the string to that function definition, or a hint, link, or whatever to the right way to do this will be highly appreciated.
Thanks
<script type="text/javascript">
$('.suggestable').live('keyup', ( function() { suggest(this); } ));
function suggest(inputTextField)
{
var inputString = inputTextField.value;
var lookFor = $(inputTextField).attr('data-lookfor');
if(inputString.length == 0) {
// $('#suggestions').fadeOut();
} else {
$.post(AjaxVars.url,
{
action: 'suggest-submit',
queryString: ""+inputString+"",
lookFor: ""+lookFor+""
},
function(data)
{
// Clear the target div in a very very ugly way
document.getElementById('suggestionsList').innerHTML = "";
var myul = document.createElement('ul');
data = data.split("\n");
for(var index in data)
{
elem = data[index];
if(elem.length > 0)
{
var myli = document.createElement('li');
myli.innerHTML = elem;
//////////////////////////////////////
myli.onclick=(function() { fill(inputTextField, elem); });
//////////////////////////////////////
myul.appendChild(myli);
}
}
document.getElementById('suggestionsList').appendChild(myul);
});
}
}
function fill(object, thisValue) {
object.value = thisValue;
// setTimeout("$('#suggestions').fadeOut();", 600);
}
</script>