如何删除自动完成中的重复项

时间:2012-10-26 12:09:28

标签: jquery

<html>
<head>
  <script src=".\jquery.1.4.2.js"></script>
  <link rel="stylesheet" enter code heref=".\jquery.autocomplete.css" type="text/css" />   
  <script type="text/javascript" src=".\jquery.autocomplete.js"></script>

  <script>
  $(document).ready(function(){
      var data = "AndraPradesh;ArunachalPradesh;Assam;Bihar;Chhattisgarh;Goa;Gujarat;Haryana;HimachalPradesh;Jammuan&Kashmir;Jharkhand;Karnataka;Kerala;MadyaPradesh;Maharashtra;Manipur;Meghalaya;Mizoram;Nagala;Orissa;Punjab;Rajasthan;Sikkim;TamilNadu;Tripura;Uttaranchal;UttarPradesh;WestBengal".split(";");

   $("#example").autocomplete((data),{ matchContains: 0, minChars: 1, scroll: true, width: 143, selectFirst: true, multiple: true, multipleSeparator: ';', autoFill: false });
});
  </script>

</head>
<body>
<b><font color="red">ENTER INDIAN 'STATE' NAME TO SEE AUTOCOMPLETE</font></b>
<br><br> Enter States <input id="example" /> <button onclick="javascript:displaycontent();">click me</button>
</body>
<script>
function displaycontent()
{
var alertmsg = $("#example")[0].value;
alert(alertmsg );
}
</script>
</html>

我使用上面的代码....一旦我输入州名....当我们输入另一个州名时,它不应出现在下一次尝试中

1 个答案:

答案 0 :(得分:4)

我详细阐述了henkieee的评论:

var data = "AndraPradesh;ArunachalPradesh;Assam;Bihar;Chhattisgarh;Goa;Gujarat;Haryana;HimachalPradesh;Jammuan&Kashmir;Jharkhand;Karnataka;Kerala;MadyaPradesh;Maharashtra;Manipur;Meghalaya;Mizoram;Nagala;Orissa;Punjab;Rajasthan;Sikkim;TamilNadu;Tripura;Uttaranchal;UttarPradesh;WestBengal".split(";");

var distinct = [];

$.each(data , function(i, el){
    if($.inArray(el, distinct ) === -1) 
        distinct.push(el);
});

//distinct will not contain any duplicates

或者如果你不想使用jquery(不会在ie7中工作):

var distinct = data.filter(function(elem, pos) {
    return data.indexOf(elem) == pos;
});

Fiddle