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.

有帮助吗?

解决方案

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() {
...
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top