首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在WTForms无线电元素中调用Javascript函数?

如何在WTForms无线电元素中调用Javascript函数?
EN

Stack Overflow用户
提问于 2022-02-07 17:27:25
回答 1查看 121关注 0票数 0

我对wtform和烧瓶很陌生。我试图这样做,当用户更改单选按钮时,文本就会发生变化。但是,当前onchange不工作,onclick也不起作用,当我移除它时,文本就会出现,但是当按钮被更改并保持不变时,文本就不会改变了。

代码语言:javascript
复制
    {{ 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>

有人能指出我做错了什么以及该做什么吗?非常感谢你的帮助!

EN

回答 1

Stack Overflow用户

发布于 2022-02-08 00:19:01

你快到了。

wtforms.RadioField由多个输入字段组成。必须为这些输入字段中的每个字段手动注册事件侦听器。为此,我建议使用一个单独的脚本块。

代码语言:javascript
复制
{% 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 %}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71022787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档