I have a search similar to Google’s that dropsdown with results while the user is typing. Ideally I would like for the user to click on one of these results and the value goes into the searchbox. However, when i click on the results, nothing happens.
HTML:
<input type='text' id='topicInput' name='topic' autocomplete='off' />
<div id='tagResult'></div> //this is the dropdown
JQUERY:
$('#topicInput').keyup(function(){
var topic = $(this).val();
if (topic==''){
$('#tagResult').css("display" , "none");
}
else{
//$('div').click(function(){
//$('#tagResult').css("display" , "none");
//});
$('#tagResult').css("display" , "block");
$.post('../topic.php' , {topic: topic} , function(response){
$('#tagResult').html(response);
});
}
});
//the above code is working properly
$('.topicResult').click(function(){
alert(1); //this is just a test, but it never shows up
});
So, when i click on a .topicResult nothing happens. An alert should show up. I have verified that topic.php does in fact return divs with the topicResult class.
You’re binding your click event and then adding elements to the page after the listener is bound. It won’t fire.
Two options
Option 1, use a listener that can bind to elements after the page is rendered
Either change the click event for .topicResult to use “.on()” for jQuery 1.7+ or use “.live() or .delegate()” for previous versions
Option 2, move your click bind so it is bound after you add the elements