WTForms-Javascript:将 onclick 传递给 WTF 字段 [英] WTForms-Javascript: pass onclick to WTF field

查看:32
本文介绍了WTForms-Javascript:将 onclick 传递给 WTF 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将onclick"传递到 WTForm 字段上?我想根据是否选择了 WTF 复选框来启用/禁用字段.但是来自 WTForms 的 HTML 没有创建或具有onclick"参数.

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.

我有一个表格:

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 是:.它不起作用,因为 onclick 不存在.

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.

我已经尝试过 checkbox=BooleanField('Checkbox', onclick="disablefld()") 但这是一个意想不到的参数.这是可能的还是我应该只用纯 html 制作表单?

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?

推荐答案

您需要在呈现表单时传递额外的参数.

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

这篇关于WTForms-Javascript:将 onclick 传递给 WTF 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆