我对wtform和烧瓶很陌生。我试图这样做,当用户更改单选按钮时,文本就会发生变化。但是,当前onchange不工作,onclick也不起作用,当我移除它时,文本就会出现,但是当按钮被更改并保持不变时,文本就不会改变了。
{{ 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>有人能指出我做错了什么以及该做什么吗?非常感谢你的帮助!
发布于 2022-02-08 00:19:01
你快到了。
wtforms.RadioField由多个输入字段组成。必须为这些输入字段中的每个字段手动注册事件侦听器。为此,我建议使用一个单独的脚本块。
{% 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 %}https://stackoverflow.com/questions/71022787
复制相似问题