-1

Okay I am sure this is simple but I have gone over this a million times but can't figure out how to get the following to work. Previously I had been using live() which works absolutely fine. After moving to the "on" with the latest jQuery it no longer works. Below is a simplified version of my code. I have a search field, which on keyup returns a list of items with class "result" from an ajax call (search). I then want to target these returned elements.

$("input#search").on("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $("ul#results").fadeOut();
    }else{
        $("ul#results").fadeIn();
        $(this).data('timer', setTimeout(search, 100));
    };

});
$("li.result").on("click", function(e) {
    $(".selected").removeClass("selected");
    $(this).addClass("selected");
});
Mikka23
  • 11
  • 2
  • Have you checked the documentation about `$.live()`? They even provide exact examples how to do that. http://api.jquery.com/live/ – zerkms Sep 09 '13 at 23:57
  • 2
    Sorry, not to sound offensive but this a [RTFM](http://api.jquery.com/on/#direct-and-delegated-events) question which has been asked hundreds of times since `.live()` was deprecated years ago. – Fabrício Matté Sep 10 '13 at 00:01

1 Answers1

1

If these elements are being created dynamically (which it sounds like they are), you'll need to attach the events to a known parent and then filter accordingly:

$("body").on("click", 'li.result', function(e) {
    $(".selected").removeClass("selected");
    $(this).addClass("selected");
});
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • 1
    Wow, I need to go to sleep. I originally had that, but I have 3 instances of the same code open in my browser and must have been looking at the wrong output. This works. – Mikka23 Sep 10 '13 at 00:08