Wignu
Wignu

Reputation: 77

Jquery Live Search Only Inputs First Result In List

Am using the following code to perform a livesearch via a SQL query. The Jquery code is shown below:

$(document).ready(function() {
    $('#holdername').on('keydown', function() {
        var searchKeyword = $(this).val();
        if (searchKeyword.length >= 3) {
            $.post('holdersearch.php', { keywords: searchKeyword }, function(data) {
            $('ul#liveSearchList').empty()
            $.each(data, function() {
            $('ul#liveSearchList').append('<span class="searchResultItem"><a href="#?hldr=' + this.id + '">' + this.holder + '</a></span></br>'); 
                });
                }, "json").fail($('ul#liveSearchList').empty()); 
            } else {
                $('ul#liveSearchList').empty() 
            };
        });
    $('#liveSearchList').on('click', function() {
        var holderName = $(this).find("a").html();
        console.log("Holder: ",holderName);
        $('#holdername').val(holderName);
        $('ul#liveSearchList').empty()
    });
});

This creates the list as it should however when any item in the list is selected (clicked) it will only ever populate the input box with the first item in the list. Am not sure why it is doing this, if I hover down the list the link shows the different values for hldr as it should so it appears it is working as it should. The console.log confirms the item selected is only ever the first on the list

Upvotes: 0

Views: 109

Answers (1)

Leopold Stoch
Leopold Stoch

Reputation: 51

You added click event on whole ul, so $(this).find("a").html(); select all <a> elements and return value of first

You should add click event to all <li> or <a> elements. Try this:

$('#liveSearchList').on('click', 'li', function() {
    var holderName = $(this).find("a").html();
    console.log("Holder: ",holderName);
    $('#holdername').val(holderName);
    $('ul#liveSearchList').empty()
});

Upvotes: 1

Related Questions