jquery autocomplete - 需要输入键来处理当前搜索短语

时间:2013-09-11 12:28:35

标签: jquery jquery-ui-autocomplete

当我从自动填充中获得建议列表时,我需要允许用户只需按Enter即可处理他们输入的搜索字词,或单击其中一个建议。现在按回车键似乎提交表格(没有动作)。

<script type="text/javascript" language="JavaScript">
    jQuery( document ).ready(function($) {

     $('#SearchPhrase').autocomplete({
            source: function(query, response) {
                $.ajax({
                    url: "/services/search.cfc?method=getMessages&returnformat=json",
                    dataType: "json",
                    data: {
                        term: query.term
                    },
                    success: function(result) {
                        response(result);
                    }
                });
            }
            ,
            minLength: 3,
            select: function(event, ui) {
               alert(ui.item.value);
            $.ajax({
                    url: "/services/search.cfc?method=getMessages2&returnformat=json",
                    dataType: "json",
                    data: {
                        term: ui.item.value
                    },
                    success: function(result) {
                        alert(result.id);
                    }
                });
            }
        }).keydown(function(e){
            if (e.keyCode === 13){
                alert('enter was pressed');
                event.preventDefault();
                 $.ajax({
                    url: "/services/search.cfc?method=getMessages2&returnformat=json",
                    dataType: "json",
                    data: {
                        term: $('#SearchPhrase').val()
                    },
                    success: function(result) {
                        alert(result.id);
                    }
                });
            }
        });

        });
</script> 

1 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

function sendSelected(_val){
   var search_input = _val;
   if (search_input =='') search_input ='*';
   var dataString = 'keyword='+search_input;

   if (search_input.length > 2 || search_input=='*') {
      $.ajax({
           type: "GET",
           url: "core/functions/searchdata.php",
           data: dataString,
           success: function(server_response) {
               $('#searchresultdata').empty();
               $('#searchresultdata').append(server_response);
               $('span#category_title').html(search_input);
           }
       });
   }
}

$("#SearchPhrase").keypress(function(e) {
 if(e.keyCode == 13)
 {
     e.preventDefault();
     sendSelected(this.value);
     $(this).autocomplete('close');
 }

});