WTForms-Javascript: pass onclick to WTF field

爱⌒轻易说出口 提交于 2019-12-11 07:02:27

问题


Is there a way to pass "onclick" onto a WTForm field? I'd like to enable/disable a field depending on whether a WTF checkbox is selected. But the HTML from WTForms does not create or have an "onclick" parameter.

I have a form:

class test(Form):
    checkbox=BooleanField('Checkbox')
    required=TextField('Required if checked')

and I have the JS:

function disablefld(){
  cb=document.getElementById('checkbox').checked;
  document.getElementById('required').disabled=!cb;
  }

The HTML WTForms generated for the checkbox is: <input id="checkbox" name="checkbox" type="checkbox" value="y">. It doesn't work becauseonclick is not present.

I've tried checkbox=BooleanField('Checkbox', onclick="disablefld()") but it is an unexpected argument. Is this possible or should I just make the form in pure html?


回答1:


You need to pass the extra arguments while rendering your form.

{% 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 %}


来源:https://stackoverflow.com/questions/50747582/wtforms-javascript-pass-onclick-to-wtf-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!