javascript - How to not allow values that are not in the database in an Autocomplete form with PHP & JS

70

I have an autocomplete function with a form where the name of the city is type into. All possible values are in a database and are pull out of the database and store them in the variable $list

Then I have my form with the input and the button

<form name="form1" method="post" action="searchresults.php" >
    <input id="hero-demo" autofocus type="search" name="search" placeholder="City" >
    <input type="submit" name="submit" value="Search">
</form>

and the autocomplete function:

   <script>
    $(function(){
        $('#hero-demo').autoComplete({
            minChars: 1,
            source: function(term, suggest){
                term = term.toLowerCase();
                var choices = [<?= $list ?>];
                var suggestions = [];
                for (i=0;i<choices.length;i++)
                    if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
                suggest(suggestions);
            }
        });

    });

</script>

How can I do, so if for instance the user introduce the value "London" and that value is not in my database ($list) then the Search button doesn't work.

Thank you very much

599

Answer

Solution:

You could add onsubmit event in your js code then do what you want before submiting the form and you should remove inline-event from your HTML code in this case.

HTML :

<form name="form1" method="post" action="searchresults.php" >

JS :

$('form[name="form1"]').on('submit', function(e){
     //Prevent form submiting after click on submit button
     e.preventDefault(); 

     //Do what you want
     $('#hero-demo').blur();

     //Submit the form
     $(this).submit();
});

Hope this helps.

People are also looking for solutions to the problem: php - wamp rewrite_module not getting ticked

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.