0

I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autocomplete widget to help user select one option. I know I'm terribly off the track.

My json file:

[
    {"iata":"AAC", "name":"El Arish"},
    {"iata":"AAE", "name":"Annabah"},
    {"iata":"AAF", "name":"Apalachicola"},
    {"iata":"AAG", "name":"Arapoti"},
    {"iata":"AAH", "name":"Aachen"},
    {"iata":"AAI", "name":"Arraias"},
    {"iata":"AAJ", "name":"Awaradam"},
    {"iata":"AAK", "name":"Buariki"},
    {"iata":"AAL", "name":"Aalborg"},
    {"iata":"AAM", "name":"Malamala"},
    {"iata":"AAN", "name":"Al Ain"}
]

My JavaScript:

$(document).ready(function () {
    $('#search').autocomplete({
        source: function (request, response) {
            var searchField = $('#search').val();
            var myExp = new RegExp(searchField, "i");
            $.getJSON("beta.json", function (data) {
                var output = '<ul class="searchresults">';
                $.each(data, function (key, val) {
                    if ((val.iata.search(myExp) !== -1) ||
                            (val.name.search(myExp) !== -1)) {
                        output += '<li>';
                        output += '<h2>' + val.iata + '</h2>';
                        output += '<p>' + val.name + '</p>';
                        output += '</li>';
                    }
                });
                output += '</ul>';
                $('#update').html(output);
            });
            )
            });
        }    
    });
});

2 Answers 2

3

I fixed some syntax errors and then wrote up this example to really get you jump started.

$( function() {
	$.getJSON("http://neil.computer/stack/beta.json", function(data) {
		autoComplete = [];
		for (var i = 0, len = data.length; i < len; i++) {
			autoComplete.push(data[i].name + ", " + data[i].iata);
		}
		$( "#tags" ).autocomplete({
			source: autoComplete
		});
	});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
	<label for="tags">Tags: </label>
	<input id="tags">
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you but I would like to select one of the option. Now it is just giving me an unordered list list when I search and does not allow me to select one of the option. Thats why I select autocomplete widget.
2

You can push html to an array at request, pass array to response, at .autocomplete("instance")._renderItem create an <li> element with html set to second argument item, .value property, which should be html set within request and passed to response; append <li> to first argument ul, return ul from ._renderItem

  var elem = $("#search");
  $.ajaxSetup({
    context: elem
  });
  elem.autocomplete({
      minLength: 1,
      source: function(request, response) {
        $.getJSON("beta.json")
          .then(function success(data) {
            var searchField = elem.val();
            var myExp = new RegExp(searchField, "i");
            var res = [];
            $.each(data, function(key, val) {
              if ((val.iata.search(myExp) !== -1) ||
                (val.name.search(myExp) !== -1)) {
                res.push("<h2>" + val.iata + "</h2>" + "<p>" + val.name + "</p>")
              }
            });
            response(res);

          }, function error(jqxhr, textStatus, errorThrown) {
            console.log(textStatus, errorThrown) // log `$.ajax` errors
          })
      }
    })
    .autocomplete("instance")._renderItem = function(ul, item) {
      return $("<li>", {
        html: item.value
      }).appendTo(ul)

  };

jsfiddle http://jsfiddle.net/wr1wg5df/11/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.