Extracting input from all input boxes into a list using flask

て烟熏妆下的殇ゞ 提交于 2020-06-25 07:21:28

问题


I am trying to use my flask backend to extract my input. However, in my html file, I use javascript so that I can dynamically arrange any number of input boxes I want.

<!DOCTYPE html>
<script>
function add_field()
{
  var total_text=document.getElementsByClassName("input_text");
  total_text=total_text.length+1;
  document.getElementById("field_div").innerHTML=document.getElementById("field_div").innerHTML+
  "<li id='input_text"+total_text+"_wrapper'><input type='text' class='input_text' id='input_text"+total_text+"' placeholder='Enter Text'></li>";
}
function remove_field()
{
  var total_text=document.getElementsByClassName("input_text");
  document.getElementById("input_text"+total_text.length+"_wrapper").remove();
}
</script>
{% extends "bootstrap/base.html" %}
{% block content %}

<div class = "container">
<h1>Give the words</h1>
        <form action='/results' method="post">
            <div id="wrapper">
                <input type="button" value="Add TextBox" onclick="add_field();"><input type="button" value="Remove TextBox" onclick="remove_field();">
                <ol id="field_div">

                </ol>
            </div>
            <input type='submit' value='Select'>
        </form>
</div>
{% endblock %}

My views.py is as follows:

from flask import render_template, request
from app import app
from .translit import *

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


@app.route('/results', methods=['POST'])
def results():
    words = getwds(request.form['input_text1'])
    return render_template('results.html', words=words)
  • How do I change the code in such a way that all the input boxes are extracted from in a list?

回答1:


The square bracket syntax in name attribute of input elements converts form inputs into an array. So, when you use name="input_text[]" you will get an array. This array can be handled in Flask routing using request.form.getlist method. Let's see this in action.

app.py:

from flask import Flask, render_template, url_for, request

app = Flask(__name__)

@app.route('/')
def search():
    return render_template('dynamic_input.html')

@app.route('/results', methods = ['GET', 'POST'])
def results():
    if request.method == 'GET':
        return redirect(url_for('/'))
    else:
        values = request.form.getlist('input_text[]')
        return render_template('dynamic_input_results.html',
                               values = values)

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

dynamic_input.html contains:

<!DOCTYPE html>
<script>
  function add_field()
  {
    var total_text=document.getElementsByClassName("input_text");
    total_text=total_text.length+1;
    field_div = document.getElementById("field_div");
    new_input = "<li id='input_text"+total_text+
    "_wrapper'><input type='text' class='input_text' name='input_text[]' id='input_text"+
    total_text+"' placeholder='Enter Text'></li>";
    field_div.insertAdjacentHTML('beforeend',new_input);
  }
  function remove_field()
  {
    var total_text=document.getElementsByClassName("input_text");
    document.getElementById("input_text"+total_text.length+"_wrapper").remove();
  }
</script>


<div class = "container">
  <h1>Give the words</h1>
  <form action='/results' method="post">
    <div id="wrapper">
      <input type="button" value="Add TextBox" onclick="add_field();">
      <input type="button" value="Remove TextBox" onclick="remove_field();">
      <ol id="field_div">

      </ol>
    </div>
    <input type='submit' value='Select'>
  </form>
</div>

dynamic_input_results.html contains:

<ul>
{% for value in values %}
    <li>{{value}}</li>
{% endfor %}
</ul>

Output

Figure 1: Dynamic input elements

Figure 2: Result is showing as a list after submitting the previous form

N.B.:

I have modified your JS code to prevent overriding of text input values after adding a new text box.

Updated:

Added checkbox with each textbox.

app.py:

from flask import Flask, render_template, url_for, request

app = Flask(__name__)

@app.route('/')
def search():
    return render_template('dynamic_input.html')

@app.route('/results', methods = ['GET', 'POST'])
def results():
    if request.method == 'GET':
        return redirect(url_for('search'))
    else:
        input_values = request.form.getlist('input_text[]')
        checkbox_values = request.form.getlist('input_checkbox')
        return render_template('dynamic_input_results.html',
                               input_values = input_values,
                               checkbox_values = checkbox_values)

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

dynamic_input.html:

<!DOCTYPE html>
<script>
  function add_field()
  {
    var total_text=document.getElementsByClassName("input_text");
    total_text=total_text.length+1;
    field_div = document.getElementById("field_div");
    new_input = "<li id='input_text"+total_text+"_wrapper'>";
    new_input += "<input type='text' class='input_text' name='input_text[]' id='input_text"+
    total_text+"' placeholder='Enter Text'>";
    new_input += "<input type='checkbox' name='input_checkbox' value='"+total_text+"' id='input_checkbox"+
    total_text+"'";
    new_input += "</li>";
    field_div.insertAdjacentHTML('beforeend',new_input);
  }
  function remove_field()
  {
    var total_text=document.getElementsByClassName("input_text");
    document.getElementById("input_text"+total_text.length+"_wrapper").remove();     
  }
</script>

<div class = "container">
  <h1>Give the words</h1>
  <form action='/results' method="post">
    <div id="wrapper">
      <input type="button" value="Add TextBox" onclick="add_field();">
      <input type="button" value="Remove TextBox" onclick="remove_field();">
      <ol id="field_div">

      </ol>
    </div>
    <input type='submit' value='Select'>
  </form>
</div>

dynamic_input_results.html:

<ul>
{% for value in input_values %}
    <li>{{value}}</li>
{% endfor %}
<hr>
{% for value in checkbox_values %}
    <li>{{value}}</li>
{% endfor %}

</ul>

Output:



来源:https://stackoverflow.com/questions/47083403/extracting-input-from-all-input-boxes-into-a-list-using-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!