Reputation: 7679
I found here an example of how to use radio buttons without a submit button. I failed to convert this example to Flask.
static/vehicle.js
:
$('#myform input[type=radio]').on('change', function(event) {
var result = $(this).val();
$('#result').html(result);
})
tamplates/example.html
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="{{url_for('static', filename='vehicle.js')}}"></script>
<form id="myform" action="" method="post">
{{ form.example }}
<div id="result"></div>
</form>
test.py
:
from flask import Flask, render_template
from wtforms import Form, RadioField
SECRET_KEY = 'development'
app = Flask(__name__)
app.config.from_object(__name__)
class SimpleForm(Form):
example = RadioField(
'Label', choices=[('home', 'home'), ('side1', 'side1'), ('side1', 'side1')])
@app.route('/', methods=['post', 'get'])
def hello_world():
form = SimpleForm()
if form.validate():
print(form.example.data)
else:
print(form.errors)
return render_template('example.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
Unfortunately, pressing the radio buttons seems not to print the value.
What did I miss?
Thank you in advance
Upvotes: 0
Views: 952
Reputation: 1863
When it comes to JS you are trying to bind handler to change event when document is not ready and automatic form submission is missing.
It works when you put your code in $( document ).ready()
callback and add $('#myform').submit();
:
$( document ).ready(function() {
$('#myform input[type=radio]').on('change', function(event) {
var result = $(this).val();
$('#result').html(result);
$('#myform').submit();
});
});
However some changes to test.py
need to be done in order to make it a working example:
from flask import Flask, render_template, request
from wtforms import Form, RadioField
SECRET_KEY = 'development'
app = Flask(__name__)
app.config.from_object(__name__)
class SimpleForm(Form):
example = RadioField(
'Label', choices=[('home', 'home'), ('side1', 'side1'), ('side1', 'side1')])
@app.route('/', methods=['post', 'get'])
def hello_world():
form = SimpleForm(request.form)
if request.method == 'POST':
if form.validate():
print(form.example.data)
else:
print(form.errors)
return render_template('example.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
You didn't pass request data to your form which always resulted in error and form validation should be performed only when it's POST request.
Upvotes: 1