JS simple autocomplete – najprostiji način

AJAX autocomplete formiran pomoću HTML5 datalist taga

$("#city_autocomplete").attr("list", "city_datalist").after('<datalist id="city_datalist"></datalist>');
$("#city_autocomplete").on('input', function() {
    var term = $(this).val(); 
    if (term.length == 1){
        $.getJSON(url_view + '?ajax=autocomplete', {type: 'brand', term: term}, function(data){
            var j = data;
            var elem = $("#city_datalist");
            var options = '';
            for (var o = 0; o < j.length; o++) {
                options += '<option value="' + j[o].title + '" id="' + j[o].id + '" data-name="' + j[o].name + '">';
            }
            elem.html(options);
            $(this).val(term);
        });            
    }
});
$("#city_autocomplete").change(function(){
    var needle = $(this).val();
    var haystack = $("#city_datalist");
    var val = $(haystack).find('option[value="' + needle + '"]');
    var endval = val.attr('id');
    $("#city_id").val(endval);
});

2 thoughts on “JS simple autocomplete – najprostiji način”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.