質問

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