views:

500

answers:

3

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>
+2  A: 

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());
});
Alex Barrett
That's a more complete answer than mine :)Great catch!
changelog
A: 

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.

changelog
+1  A: 

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());
});
Gabriel Hurley