Home > Enterprise >  Displaying table as per selected values in dropdown in flask python
Displaying table as per selected values in dropdown in flask python

Time:10-17

Below is the flask application. I have a list of values in dropdown. So I need a table corresponding to value selected in the dropdown . But right now, all the value as table is displayed app.py

from flask import Flask, render_template
import pandas as pd
import sqlalchemy as sal
from sqlalchemy import create_engine
import pyodbc 
import urllib


app = Flask(__name__)

list_ticker = ['Com1', 'Com2', 'Com3', 'Com4']


@app.route('/', methods=['GET'])
def dropdown():
    colours = list_ticker
    return render_template('template.html', tickers = colours)

if __name__ == "__main__":
    app.run(port = 8080)

template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dropdown</title>
</head>
<body>
<select name="ticker" method="GET" action="/" onchange="update_selected_event(event)">
    {% for ticker in tickers %}
        <option value="{{ticker}}" SELECTED>{{ticker}}</option>
    {% endfor %}
</select>
<br></br>

<span>The selected table is actually </span>
<table id="res" name="ticker" method="GET" action="/">
{% for ticker in tickers %}
  <tr>
    <th>{{ticker}}</th>
    <th>{{ticker}}</th>
  </tr>
  <tr>
    <td>{{ticker}}</td>
    <td>{{ticker}}</td>
  </tr>
  {% endfor %}
</table>



<script>function update_selected_event(event) {document.getElementById('res').innerHTML = event.target.value;}
</script>
</body>
</html>

Actual output enter image description here

Expected output Only selected value as table should be displayed

CodePudding user response:

Couple of feedbacks:

  1. We're looping through all tickers and print them as table row.
  2. We're setting table innerHTML directly as clear text.

We can try something like this:

function update_selected_option_value(value) {
  document.getElementById('res_head').innerHTML = value;
  document.getElementById('res_data').innerHTML = value;
}
<select onchange="update_selected_option_value(this.value)">
  <option value="Apple">Apple</option>
  <option value="Banana">Banana</option>
  <option value="Mango">Mango</option>
<select>

<table name="ticker" method="GET" action="/">
  <tr>
    <th id="res_head">---</th>
  </tr>
  <tr>
    <td id="res_data">---</td>
  </tr>
</table>

  • Related