Reputation: 6941
code below for a simple auto suggest box... however when I click a suggestion from the list it doesn't return the contents to the input box like it should. It doesn't recognize anything from the loaded html at all?
JQUERY
$(document).ready(function(){
$('#edit-name').keyup(function() {
if ($(this).val().length >= 3) {
bname = $(this).val();
$("#searchframe").load("searchresults.php", { 'name[]': [name] });
} else {
$("#searchframe").html('');
}
});
$('.bus').click(function() {
alert("testing"); // <-- nothing happens!
$('#edit-name').val($(this).html());
});
});
HTML
...
<body>
...
<input type="text" id="edit-name" />
<div id="searchframe"></div>
...
</body>
...
INJECTED HTML
<ul>
<li><a href="#" class="bus">test1</a></li>
<li><a href="#" class="bus">test2</a></li>
</ul>
Upvotes: 0
Views: 2751
Reputation: 40062
Your elements with the "bus" class are not present at DOM load (you're injecting them later dynamically) so your click function isn't applied.
You can use jQuery's live() method to apply your click function to all elements that are added dynamically.
$('.bus').live('click', function() {
alert("testing"); // <-- nothing happens!
$('#edit-name').val($(this).html());
});
Upvotes: 1
Reputation: 4681
You're setting the click event before the DOM from the autocomplete suggestions is loaded.
Try adding that action inside the injected HTML and let me know how it goes.
Upvotes: 0
Reputation: 16465
The click event is bound on document load, and the HTML is injected after this has happened. I would recommend using the live
method, which will bind the event to all current and future elements on the page.
$('.bus').live('click', function() {
alert("testing"); // <-- something (should) happen!
$('#edit-name').val($(this).html());
});
Upvotes: 2