【问题标题】:Store and Access Each Radio Button Click存储和访问每个单选按钮单击
【发布时间】:2020-09-21 07:29:51
【问题描述】:

我想将每个单选按钮选择存储为一个数组。

例如,给定 2 个单选按钮,如果用户 a 选择第一个,然后选择第二个,然后再次选择第一个,我想要一个 [1,2,1] 数组。

这里是questions.html

<html>
<head>
    <title></title>
</head>
<body>
    {% for post in posts %}
        <h1>Question {{ post.Number }}</h1>
        <h2> {{ post.Question }}</h2>
            {% for choice in post.Choices %}
    <form>
                <input type="radio" name="choice" id="{{ post.Number }}{{ choice[0] }}" value="{{ choice[0] }}"> {{ choice[1] }}</input><br>
            {% endfor %}
    </form>
    {% endfor %}
</body>
</html>

这里是flask_main.py

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

post = [
    {'Number': '1',
     'Statement': 'the question',
     'Choices': [('a', 'words'),
                 ('b', 'words')]
     },
    {'Number': '2',
     'Statement': 'the question',
     'Choices': [('a', 'words'),
                 ('b', 'words')]
     }
       ]

@app.route('/')
@app.route("/questions")
def questions():
    return render_template('questions.html', posts=post)


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

【问题讨论】:

    标签: javascript python html flask jinja2


    【解决方案1】:

    基本上这与服务器端(= Python)无关。

    首先,确保所有单选按钮都在一个表单中,否则它们将被视为在不同的组中(也就是可以选择多个)。

    然后您可以创建一个数组,并在change 事件中将修改后的收音机的id(或您想要存储的任何内容)添加到数组中。

    现在只是你对数组做什么的问题。将其显示在页面的某处或将其发送回服务器。

    在纯 JS 中查看下面的示例。

    let choices = [];
    let radios = document.getElementsByClassName("my-radio");
    
    for (let radio of radios) {
      radio.addEventListener("change", (event) => {
        choices.push(event.target.id);
        document.getElementById("output").innerHTML = choices;
      });
    }
    <h1>Question 1</h1>
    <form>
      <input type="radio" class="my-radio" name="choice" id="question-1" value="choice-1">
        choice 1
      </input>
      <br>
      <input type="radio" class="my-radio" name="choice" id="question-2" value="choice-2">
        choice 2
      </input>
    </form>
    <p id="output"></p>

    【讨论】:

    • 这看起来和我要找的完全一样!我现在将尝试实施它并返回 Qs。非常感谢!
    • 你能帮我把阵列发回服务器吗?
    猜你喜欢
    • 2013-06-05
    • 2016-11-10
    • 1970-01-01
    • 2014-05-02
    • 2021-12-02
    • 2019-09-15
    • 2012-02-03
    • 2011-12-03
    • 1970-01-01
    相关资源
    最近更新 更多