Fraz Fraz - 2 months ago 23
HTML Question

Autocomplete search box and pass value to flask

I am preparing a demo and this is the first time I am doing "web dev".
So, might be totally a noob question but here is what I am trying to do.

I want to have two search boxes which autocompletes as typing.

First search box: name
Second search box: song


I have two files names.txt and songs.txt

So, the idea is that when the user is typing name, it is reading from names.txt to generate the autocomplete and when user is typing song, the search box autocompletes based on songs.txt

And then these values are passed to flask app in backend..

@app.route('/search', method=['post'])
def process():
return name, song, and list of other songs with score (list a table)


I need like a very simple example (nothing fancy) which just does this..

Thanks

Answer

How about using jQuery-Autocomplete. This should get you started:

**/app.py**

from flask import Flask, request, render_template, jsonify
app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/search/<string:box>")
def process(box):
    query = request.args.get('query')
    if box == 'names':
        # do some stuff to open your names text file
        # do some other stuff to filter
        # put suggestions in this format...
        suggestions = [{'value': 'joe','data': 'joe'}, {'value': 'jim','data': 'jim'}]
    if box == 'songs':
        # do some stuff to open your songs text file
        # do some other stuff to filter
        # put suggestions in this format...
        suggestions = [{'value': 'song1','data': '123'}, {'value': 'song2','data': '234'}]
    return jsonify({"suggestions":suggestions})

if __name__ == "__main__":
    app.run(debug=True)

**/templates/index.html**

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.26/jquery.autocomplete.min.js"></script>
</head>

<body>
  Names:
  <input type="text" name="names" id="autocomplete1"/>

  Songs:
  <input type="text" name="songs" id="autocomplete2"/>


  <script>
  $('#autocomplete1').autocomplete({
      serviceUrl: '/search/names',
      dataType: 'json',
      onSearchComplete: function (query, suggestions) {
        console.log(query);
      }
  });

  $('#autocomplete2').autocomplete({
      serviceUrl: '/search/songs',
      dataType: 'json',
      onSearchComplete: function (query, suggestions) {
        console.log(query);
      }
  });
  </script>
</body>