Question

I am trying to write an autosuggest function for a searchbox. It seems to be doing what I want in all but one respect. All suggestions are for the previous keystroke rather than the current (the latest suggestion does not account for the latest key pressed).

My Javascript / JQuery code is as follows:

$('#searchBox').keypress(function() {
    if ($('#suggest').length < 1) {
        $('.search').append('<div id="suggest"></div>');
    }
    search_text = $('#searchBox').val();
    $.ajax({ url: '<?php echo base_url('home/get_suggestions'); ?>',
        data: {"search_text": search_text},
        type: 'post',
        async: 'false',
        success: function(data) {
            $('#suggest').html(data);
        }
    });
});
$('#searchBox').blur(function() {
    $('#suggest').remove();
});

Any help would be appreciated. Thanks.

Était-ce utile?

La solution

Try using the keyup event. In the keydown or the keypress event the textbox has the "previous" value, while the keyup event has the "new" value.

$('#searchBox').keyup(function() {
...
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top