首页 > 解决方案 > 从选择字段填充表单字段的最佳方式

问题描述

我正在提供一个烧瓶应用程序并尝试使用 jquery 根据下拉菜单中的信息填充表单字段。

应用程序.py

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


@app.route('/', methods=['GET', 'POST'])
def index():
    cats = [{'name': 'fluffy', 'size': 'big'}, {'name': 'smelly', 'size': 'small'}]
    if request.method == 'GET':
        return render_template('index.html', cats=cats)
    elif request.method == 'POST':
        return "thanks"


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

索引.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form class="" action="/" method="post">
      <select>
        {% for cat in cats %}
          <option size={{ cat['size'] }}>{{ cat['name'] }}</option>
        {% endfor %}
      </select>
      <input type="text" name="size" value="">
      <input type="submit" value="Submit">
    </form>
  </body>

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>
</html>

我正在寻找的是一个放入 index.html 的脚本,它监视 cat 选择并使用选项中的大小值填充大小输入。

我应该注意这个输入应该保持可编辑,所以我可以在选择后覆盖大小输入。如果脚本仅在不包含值的情况下填充大小输入,则加分。

标签: pythonjqueryhtmlflask

解决方案


python(添加了没有已知大小的猫)

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


@app.route('/', methods=['GET', 'POST'])
def index():
    cats = [{'name': 'fluffy', 'size': 'big'},
            {'name': 'smelly', 'size': 'small'}, 
            {'name': 'Mr Meow', 'size': None}]
    if request.method == 'GET':
        return render_template('test.html', cats=cats)
    elif request.method == 'POST':
        return "thanks"


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

js:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <form class="" action="/" method="post">
    <select onChange="changeSizeInput()" id="catSelect">
    {% for cat in cats %}
      <option size={{ cat['size'] }}>{{ cat['name'] }}</option>
    {% endfor %}
  </select>
    <input type="text" name="size" id="catSize">
    <input type="submit" value="Submit">
  </form>
</body>

<script>
  function changeSizeInput() {
    var cat = document.getElementById('catSelect')
    var size = cat.options[cat.selectedIndex].getAttribute("size");
    if (size == 'None') {
      size = ''
    }
    document.getElementById('catSize').value = size;
  }
  changeSizeInput()
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
</script>
</html>

所以诀窍是在你的选择菜单中有一个事件监听器,当你的猫被改变时执行。之后,它将查找所选猫的大小,然后使用所选猫的大小更新输入。如果大小为None,则将大小设置为空字符串。该函数在加载页面时也会执行,因此它也会加载选择框中的第一只猫。

这有点难看,因为 pythonNone并没有真正授予 javascript null,但它会完成这项工作。

对于 jquery,将代码更改为:

function changeSizeInput() {
  var size = $('#catSelect option:selected').attr('size')
  if (size == 'None') {
    size = ''
  }
  $('#catSize').val(size);
}
changeSizeInput()

推荐阅读