Open In App

Live Search Using Flask And jQuery

Last Updated : 09 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will do a live search in Flask using Jquery. Live search means that whenever a user type any letter in the input box then all the words containing that letter will be shown.

Installation

This module does not come in-built with Python. To install it type the below command in the terminal.

pip install flask

After installing the flask create a new directory for the project. Inside that create a new file and name that app.py. 

Python3




from flask import Flask,render_template
  
  
app = Flask(__name__)
  
@app.route("/")
def home():
    return render_template("index.html")
  
  
if __name__ == "__main__":
    app.run(debug=True)


Inside the project create new directory templates and inside that create a new file index.html. This file contains the HTML code for user input where user will input the desired text and the output will be shown. The Jquery will search for the all the strings containing the matching character(s) typed by the user.

Index.HTML

HTML




<!DOCTYPE html>
<html>
<head>
    <title>GFG</title>
</head>
<body>
  
<input type="text" class="live-search-box" placeholder="search here" />
  
<ul class="live-search-list" type="None">
<li>C++</li>
<li>c</li>
<li>Python</li>
<li>Java</li>
<li>Javascript</li>
<li>Golang</li>
<li>R</li>
<li>Ruby</li>
<li>Scala</li>
<li>C#</li>
<li>PHP</li>
<li>Fortran</li>
<li>Dart</li>
</ul>
  
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
  
<script type="text/javascript">
    jQuery(document).ready(function($){
  
$('.live-search-list li').each(function(){
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
  
$('.live-search-box').on('keyup', function(){
  
var searchTerm = $(this).val().toLowerCase();
  
    $('.live-search-list li').each(function(){
  
        if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
            $(this).show();
        } else {
            $(this).hide();
        }
  
    });
  
});
  
});
</script>
  
</body>
</html>


To run this app open cmd or terminal in the same directory and type the below command.

python app.py

Output:

live search flask



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads