WTForms-Javascript:将onclick传递给WTF字段

时间:2022-11-23 13:10:31

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.

有没有办法将“onclick”传递到WTForm字段?我想根据是否选中WTF复选框来启用/禁用字段。但来自WTForms的HTML不会创建或具有“onclick”参数。

I have a form:

我有一个表格:

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

and I have the JS:

我有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.

为复选框生成的HTML WTForms为:。它不起作用因为没有单击。

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?

我试过checkbox = BooleanField('Checkbox',onclick =“disablefld()”),但它是一个意外的参数。这是可能的还是我应该用纯HTML制作表单?

1 个解决方案

#1


0  

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

#1


0  

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