1

当我有一个来自自动完成的建议列表时,我需要允许用户按 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> 
4

1 回答 1

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');
 }

});

于 2014-09-24T05:25:38.603 回答