Reputation: 867
I would like to store every radio button selection as an array.
For example, given 2 radio buttons, if a user a selects the first, then the second, then the first again, I would like an array of [1,2,1]
.
Here is 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>
Here is 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)
Upvotes: 0
Views: 173
Reputation: 81654
Basically this is not related to the server-side (= Python).
First, make sure all the radio buttons are inside a single form otherwise they will be considered as being in a different group (AKA it will be possible to select more than one).
Then you can create an array, and inside the change
event add the id
(or whatever you want to store) of the modified radio to the array.
Now it is just a matter of what you are doing with the array. Display it somewhere on the page or send it back to the server.
See the example below in pure 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>
Upvotes: 2