문제

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