Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery text field auto complete

Hello guys so I have the following issue.

I have the following autocomplete made for myself and I want when the user enters invalid city to show under the textbox "no match found" or "no city found" etc.

Here is my Jquery.

(P.S.) I need it to work without any autocomplete plugins etc.

$('.form-control').keyup(function(e){
    e.preventDefault();
    $.ajax({
        method: "GET",
        url: "https://api.teleport.org/api/cities?search=" + $('.form-control').val(),

}) .done(function(data){
        if(typeof data._embedded["city:search-results"][0] === 'undefined') {
            $('#datalist').append('Please select a valid value.');
        } else {
    console.log(data._embedded["city:search-results"][0].matching_full_name);
    $('option:eq(0)').remove();
    $('#datalist').append('<option value="' + data._embedded["city:search-results"][0].matching_full_name + '">');
}

});
});
like image 863
Stiliyan Avatar asked Apr 27 '26 16:04

Stiliyan


1 Answers

Is this what you're trying to achieve?

$('.form-control').keyup (function (e) {
    e.preventDefault ();
    $.ajax ( {
        method: "GET",
        url: "https://api.teleport.org/api/cities?search=" + $('.form-control').val (),

    } )
    .done ( function(data){

        if(typeof data._embedded["city:search-results"][0] === 'undefined') {
            $('#datalist').html ('');
            $('#datalist').html ('No Match Found');
        }
        else {
            console.log (data._embedded["city:search-results"][0].matching_full_name);
            $('#datalist').html ('');
            $('option:eq(0)').remove ();
            $('#datalist').html ('<option value="' + data._embedded["city:search-results"][0].matching_full_name + '">' + data._embedded["city:search-results"][0].matching_full_name + '</option>');
        }

    });
});
like image 104
Danny Pearson Avatar answered Apr 30 '26 06:04

Danny Pearson