Saturday, 4 May 2019

custom autocomplete with json

Want to display custom Autocomplete from set of the following JSON file,

[
{"full_name":"Meena Khadikar","slug":"meena-khadikar","people_id":"630","name":"kumar,prabhu"},
{"full_name":"Meena","slug":"meena","people_id":"817","name":""},
{"full_name":"Seshadri Meenakshi","slug":"meenakshi-seshadri","people_id":"1410","name":"meenan kumaran"}
]

If my input is mee means, result should be like

  • Meena Khadikar
  • Meena
  • Seshadri Meenakshi

If input is kum means,

  • Meena Khadikar (kumar,prabhu)
  • Seshadri Meenakshi (meenan kumaran)

Having following Script,

    $( ".search_name" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var inp = request.inp;
            if ( inp in cache ) {
                response( cache[ inp ] );
                return;
            }
        $.getJSON( "<?php echo PROJECT_PATH.'searchProfile'; ?>", {inp: request.inp}, function( data, status, xhr ) {
            cache[ inp ] = data;                    
            response( data );
            });            
    $.ui.autocomplete.prototype._renderItem = function (ul, item) {
                item.full_name = item.full_name.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.inp) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
                return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append('<a href="<?php echo PROJECT_PATH.'searchProfile'; ?>'+item.slug +'/'+item.people_id + '">' + item.full_name + '</a>')
                        .appendTo(ul);
            };
        },
        select: function (event, ui) {                                                                
                var href = '<?php echo PROJECT_PATH.'searchProfile'; ?>'+ui.item.slug +'/'+ui.item.people_id;
                window.location.href = href;
        return false;
      },
      focus: function (event, ui) {
        event.preventDefault();
        $("#search_name").val(ui.item.slug);
    }

});

Edit my script in better way.



from custom autocomplete with json

No comments:

Post a Comment