A
A
Ankozar2021-03-17 10:53:17
AJAX
Ankozar, 2021-03-17 10:53:17

How to correctly select a region from the database when entering a name in a field?

Curve question, but I just don't know how it's called correctly.

Essence: The
6051b30523e5a892646142.png

user selects the region. Begins to enter the name in the field, I'm looking for the desired value in the database with Ajax.

I have this code now:

<input list='inputRegion' class="inputRegion">
<datalist id='inputRegion'>
</datalist>


$('input.inputRegion').keyup(function(e) {
    //console.log(e.which);
    if(e.which != 32){
        $("#inputRegion").empty();
        chooseRegion();
    };
});

function chooseRegion() {
    $.ajax({
            type: 'POST',
            url: 'php/chooseRegion.php',
            data: {chooseRegion: $("input.inputRegion").val()},
            success: function (response) {
                var result = $.parseJSON(response);
                $("#inputRegion").append("<option value='" + result + "'>");
                // console.log(result);
            }
        });
}


There are three questions.
1. Are the html tags chosen correctly? I mean it's input.list + datalist. Maybe select is needed?
2. Correct implementation? Or is it done in some other way?
3. How to catch the selection when the user clicks on the desired region? (here he is alone so far, but there will be a bunch of them).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Orlov, 2021-03-17
@Ankozar

Are the html tags correct? I mean it's input.list + datalist. Maybe select is needed?
The input tag "list" is redundant, it must be removed. replace datalist with select.
---
The implementation is normal, but if you want to get confused - you can send a request only at the moment when the user has stopped typing. What is discussed here - How to make ajax lookup with keyup delay to reduce load? / https://learn.javascript.ru/task/debounce
---
The choice to catch is the same as in the input.
Only if you catch the keyup event in the input, then the select will have change\onchange https://www.google.com/search?q=onchange+select+ev...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question