jqueryui autocomplete結合AJAx實現自動補全

1、項目中有需要會需要用到輸入框自動補全功能,類似於企業名,藥店名稱等等。jqueryui autocomplete就可以實現這個功能。
jquery ui AutoComplete 官網地址:http://jqueryui.com/autocomplete/

效果如下圖所示:
這裏寫圖片描述
下面來使用 autocomplete插件來實現類似效果。
代碼如下所示:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  <style>
  .ui-autocomplete-loading {
    background: white url("http://jqueryui.com/resources/demos/autocomplete/images/ui-anim_basic_16x16.gif") right center no-repeat;
  }
  </style>  
  <script>
  $( function() {
    $("#companyid").autocomplete({
            minLength: 5,  //滿足搜索的最小長度
          source: function( request, response ) {
              $.ajax({
                url: "/onWay/getCompanyName",
                type : "post",  
                dataType : "json", 
                data: {
                    companynm : $("#companyid").val()
                },
                success: function( data ) {
                  response( $.map( data.company, function( item ) {
                    return {
                      label: item.companynm,
                      value: item.id
                    }
                  }));
                }
              });
            },
            select: function( event, ui ) {
                 //設置輸入框值
                 $("#companyid").val( ui.item.label );
                 //設置id值
                 $("#company_id").val(ui.item.value);
                 return false;
            }
          });
  } );
  </script>
</head>
<body>

<input type="text" id="companyid" name="companyid" value="" filterType="="></input>
<input type="hidden" id="company_id" >

</body>
</html>
發佈了45 篇原創文章 · 獲贊 21 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章