views:

259

answers:

3

Hai guys,

Can someone help me to pass this json data to jquery automplete plugin... As i am a newbie to jquery i dont how to do it...

[{"0":"1","id":"1","1":"Albania","country":"Albania"}, 
{"0":"2","id":"2","1":"Algeria","country":"Algeria`"}, 
{"0":"3","id":"3","1":"Angola","country":"Angola"}, 
{"0":"4","id":"4","1":"Anguilla","country":"Anguilla"}, 
{"0":"5","id":"5","1":"Antigua","country":"Antigua"}, 
{"0":"6","id":"6","1":"Argentina","country":"Argentina"}, 
{"0":"7","id":"7","1":"Armenia","country":"Armenia"}, 
{"0":"8","id":"8","1":"Aruba","country":"Aruba"}, 
{"0":"9","id":"9","1":"Australia","country":"Australia"}, 
{"0":"10","id":"10","1":"Austria","country":"Austria"}, 
{"0":"11","id":"11","1":"Azerbaijan","country":"Azerbaijan"}, 
{"0":"26","id":"26","1":"Bulgaria","country":"Bulgaria"}, 
{"0":"27","id":"27","1":"Burkina Faso","country":"Burkina Faso"}] 
A: 

http://ru2.php.net/manual/en/function.json-encode.php http://ru2.php.net/manual/en/function.json-decode.php

nex2hex
A: 

save this json to a file and link to it in the autocomplete plugin settings.

antpaw
+1  A: 

Where is the json coming from? Unless it has to be JSON, it may be better to put it in another format; the jquery.autocomplete plugin does not appear to have built in JSON handling so you would have to write handling functions yourself.

Assuming this data never changes, you can save it to a JavaScript file (say, countries.js) instead. Use the following format:

var countries = [
 { id: 1, country: "Albania" }, 
 { id: 2, country: "Algeria`" }, 
 { id: 3, country: "Angola" }, 
 { id: 4, country: "Anguilla" }, 
 { id: 5, country: "Antigua" }, 
 { id: 6, country: "Argentina" }, 
 { id: 7, country: "Armenia" }, 
 { id: 8, country: "Aruba" }, 
 { id: 9, country: "Australia" }, 
 { id: 10, country: "Austria" }, 
 { id: 11, country: "Azerbaijan" }, 
 { id: 26, country: "Bulgaria" }, 
 { id: 27, country: "Burkina Faso" }
];

Then, this is how you'd call the plugin in your main file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>

<script src="jquery.js"></script>
<script src="jquery.autocomplete.js"></script>
<script src="countries.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />

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


 $("#menu").autocomplete(countries, {
  minChars: 0,
  width: 310,

  matchContains: true,
  autoFill: false,
  formatItem: function(row, i, max) {
   return row.country;
  },
  formatMatch: function(row, i, max) {
   return row.country;
  },
  formatResult: function(row) {
   return row.id;
  }
 });

});

</script>

</head>

<body>

 <form autocomplete="off">
  <p>
   <label>Countries:</label>
   <input type="text" id="menu" />
   <input type="button" value="Get Value" />
  </p>

</body>
</html>
Jordan Reiter