I'm new to wtforms and flask. I'm trying to do so that when that a user changes the radio buttons, the text would change. However, currently the onchange does not work, nor does onclick and when I remove it, the text appears but does not change at all when the buttons are changed and remains the same.
{{ wtf.form_field(form.doc, class="form-control", onchange="myFunction()") }}
</div>
<p id="demo"></p>
<script>
function myFunction(){
if (document.getElementById('doc-0').checked) {
value = document.getElementById('doc-0').value;
document.getElementById("demo").innerHTML = "You selected: " + value;
}
else if ( document.getElementById('doc-1').checked) {
rate_value = document.getElementById('doc-1').value;
document.getElementById("demo").innerHTML = "You selected: " + value;
}
else if (document.getElementById('doc-2').checked) {
rate_value = document.getElementById('doc-2').value;
document.getElementById("demo").innerHTML = "You selected:" + value;
}
else {
document.getElementById("demo").innerHTML = "You selected: NOTHING" ;
}
}
</script>
Could someone point out what I'm doing wrong and what I should do. Thank you so much for the help!
You're almost there.
A wtforms.RadioField consists of several input fields. An event listener must be registered manually for each of these input fields. I recommend a separate script block for this.
{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block content %}
<div class="container">
<form class="form form-horizontal" method="post" role="form">
{{ form.hidden_tag() }}
{{ wtf.form_errors(form, hiddens="only") }}
{{ form.doc.label }}
{{ wtf.form_field(form.doc) }}
</form>
<output id="result">You selected nothing.</output>
</div>
{% endblock %}
{% block scripts %}
{{super()}}
<script type="text/javascript">
(() => {
// Select all input fields by name and iterate over them.
const elems = document.querySelectorAll('input[name="doc"]');
elems.forEach(elem => {
// Register an event listener for the change event.
elem.addEventListener('change', evt => {
// Update the text as soon as there is a change.
const value = evt.target.value;
const label = evt.target.parentElement.textContent.trim();
const output = document.getElementById('result');
output.innerHTML = `You selected ${label} (${value}).`;
});
});
})();
</script>
{% endblock %}