有没有办法将“onclick”传递给 WTForm 字段?我想根据是否选中 WTF 复选框来启用/禁用字段。但是来自 WTForms 的 HTML 不会创建或具有“onclick”参数。
我有一个表格:
class test(Form):
checkbox=BooleanField('Checkbox')
required=TextField('Required if checked')
我有 JS:
function disablefld(){
cb=document.getElementById('checkbox').checked;
document.getElementById('required').disabled=!cb;
}
为复选框生成的 HTML WTForms 是:
<input id="checkbox" name="checkbox" type="checkbox" value="y">
.它不起作用,因为 onclick
不存在。
我试过了 checkbox=BooleanField('Checkbox', onclick="disablefld()")
但这是一个意想不到的论点。这是可能的还是我应该只用纯 html 制作表单?
最佳答案
您需要在呈现表单时传递额外的参数。
{% block content %}
{{ form.checkbox(onchange="doStuff()") }}
{{ form.required() }}
<script>
function doStuff(){
var checked = document.getElementById('checkbox').checked
if (checked){
document.getElementById('required').disabled = true
} else {
document.getElementById('required').disabled = false
}
}
doStuff()
</script>
{% endblock %}
关于javascript - WTForms-Javascript : pass onclick to WTF field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747582/