Suppose that I have two radio buttons (labeled 1 and 2) and some text at the bottom of the page. By default the value is -1 for the text and no check boxes are selected. If I click one of the radio buttons I want to change the value of the text to be either 1 or 2 depending on the radio input that was selected. To do so I have based the code on the AJAX call described here. Here is the code:
hello.py
from flask import ( Flask, render_template, request )app = Flask(name)
@app.route(‘/’, methods=(‘GET’, ‘POST’))
def hello():
level = -1
print(request.method)
if request.method == ‘POST’:
level = int(request.form.get(‘level’, False))
return render_template(‘test.html’, value=level)
templates/test.html
<html>
<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js”></script>
<body>
<form>
<input name=“level” type=“radio” id=“1”>1</input>
<input name=“level” type=“radio” id=“2”>2</input>
</form>
{{ value }}
</body>
<script>
$(function() {
$(‘input[type=radio]’).change(function() {
console.log( $( this ).attr(“id”));
$.ajax({
type: “POST”,
data: { level: $( this ).attr(“id”) },
success: function(response) {
console.log(“HERE”);
document.write(response);
},
});
});
});
</script>
</html>
When I call flask run, selecting either radio button will change the value to either 1 or 2 but I cannot select either radio button a second time. The page will hang on the second selection, and I am not sure what is going on.
Note: Although this may seem like overkill, I have a more complex form submission in the larger project I am working on, this is simply a MVCE.
#javascript #python #html #flask