您的位置:首页 > Web前端 > JQuery

用HTML5 & jQuery创建一个简单的自动填充(autocomplete)

2014-02-11 00:00 706 查看
AutoComplete就是指用户在文本框输入前几个字母或是汉字的时候,就能从存放数据的文本或是数据库里将所有以这些字母开头的数据提示给用户,供用户选择,提供方便。





HTML代码
<!doctype html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <title>输入自动完成及提示Demo</title>
  <link rel="stylesheet" type="text/css" media="all" href="style.css">
  <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
  <script type="text/javascript" src="js/jquery.autocomplete.min.js"></script>
  <script type="text/javascript" src="js/currency-autocomplete.js"></script>
</head>

<body>
  <div id="topbar"><a href="http://www.zjgsq.com">返回web前端</a></div>
  <div id="w">
    <div id="content">
      <h1>世界货币自动完成搜索</h1>
      <p>示例只做了4种(输入值:人民币、美元、dollar、英镑)</p>

      <div id="searchfield">
        <form><input type="text" name="currency" class="biginput" id="autocomplete"></form>
      </div><!-- @end #searchfield -->

      <div id="outputbox">
        <p id="outputcontent">选择一种货币,其结果将在这里显示。</p>
      </div>
    </div><!-- @end #content -->
  </div><!-- @end #w -->
</body>
</html>

CSS代码(这里命名为style.css)

.autocomplete-suggestions { border: 1px solid #999; background: #fff; cursor: default; overflow: auto; }
.autocomplete-suggestion { padding: 10px 5px; font-size: 1.2em; white-space: nowrap; overflow: hidden; }
.autocomplete-selected { background: #f0f0f0; }
.autocomplete-suggestions strong { font-weight: normal; color: #3399ff; }
#searchfield { display: block; width: 100%; text-align: center; margin-bottom: 35px; }

#searchfield form {
  display: inline-block;
  background: #eeefed;
  padding: 0;
  margin: 0;
  padding: 5px;
  border-radius: 3px;
  margin: 5px 0 0 0;
}
#searchfield form .biginput {
  width: 600px;
  height: 40px;
  padding: 0 10px 0 10px;
  background-color: #fff;
  border: 1px solid #c8c8c8;
  border-radius: 3px;
  color: #aeaeae;
  font-weight:normal;
  font-size: 1.5em;
  -webkit-transition: all 0.2s linear;
  -moz-transition: all 0.2s linear;
  transition: all 0.2s linear;
}
#searchfield form .biginput:focus {
  color: #858585;
}

JS代码

$(function(){
  var currencies = [
    { value: '人民币', data: '¥' },
    { value: '美元', data: '$' },
    { value: 'dollar', data: '$' },
    { value: '英镑', data: '£' },
  ];

  // 设置autocomplete从数组currencies拉取数据
  $('#autocomplete').autocomplete({
    lookup: currencies,
    onSelect: function (suggestion) {
      var thehtml = '<strong>货币名称:</strong> ' + suggestion.value + ' <br> <strong>符号:</strong> ' + suggestion.data;
      $('#outputcontent').html(thehtml);
    }
  });

Demo下载源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: