You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于选中单选按钮条件渲染表单——Jinja2+FastAPI问题求助

问题解决:Jinja模板中单选按钮触发表单显示失效

问题描述

刚接触Jinja模板和JavaScript,用FastAPI开发渲染Jinja模板的应用。添加了一对单选按钮,希望点击id为round-trip的按钮时,显示包含name为dep-loc-cb和arr-loc-cb输入框的表单。参考方案编写代码后点击无效果,测试时出现错误:TypeError: Cannot read properties of null (reading 'classList'),确认form1为null。

错误原因

你的选择器逻辑错误:document.querySelector("form[name='dep-loc-cb']")试图查找name属性为dep-loc-cb的<form>标签,但实际dep-loc-cb是<form>内部<input>的name属性,<form>本身未设置name,导致无法找到元素,form1和form2均为null。此外,未处理单程单选按钮的切换事件,切换回单程时表单不会自动隐藏。

修正方案

  1. 给目标表单添加唯一标识(如id或自定义属性),方便JS定位
  2. 修正选择器,正确获取表单元素
  3. 给两个单选按钮都绑定事件,确保切换时表单状态同步

修正后的完整代码

<div class="row mt-5 mb-3">
    <div>
        <form method="post">
            <input type="radio" id="oneway-trip" name="trip-type" placeholder="One-way trip" checked/>
            <label>One-way trip</label>
            <br>
            <input type="radio" id="round-trip" name="trip-type" placeholder="Round trip"/>
            <label>Round trip</label>
        </form>
    </div>
</div>

<div class="row mt-5 mb-3">
    <div>
        <!-- 给表单添加id用于定位 -->
        <form id="dep-cb-form" class="hidden" method="post">
            <input type="text" placeholder="from" name="dep-loc-cb" value="{{departure_location_comeback}}">
        </form>
        <form id="arr-cb-form" class="hidden" method="post">
            <input type="text" placeholder="to" name="arr-loc-cb" value="{{arrival_location_comeback}}">
        </form>
        <script>
            // 通过id获取目标表单
            const depForm = document.querySelector("#dep-cb-form");
            const arrForm = document.querySelector("#arr-cb-form");
            
            // 获取两个单选按钮元素
            const roundTripBtn = document.querySelector('#round-trip');
            const oneWayBtn = document.querySelector('#oneway-trip');
            
            // 封装显示/隐藏表单的逻辑
            function setRoundTripFormsVisible(visible) {
                if (visible) {
                    depForm.classList.remove("hidden");
                    arrForm.classList.remove("hidden");
                } else {
                    depForm.classList.add("hidden");
                    arrForm.classList.add("hidden");
                }
            }
            
            // 绑定往返单选按钮的切换事件
            roundTripBtn.addEventListener('change', (e) => {
                setRoundTripFormsVisible(e.target.checked);
            });
            
            // 绑定单程单选按钮的切换事件,确保切换回单程时隐藏表单
            oneWayBtn.addEventListener('change', (e) => {
                setRoundTripFormsVisible(!e.target.checked);
            });
        </script>
    </div>
</div>

额外验证

确保你的style.css中.hidden样式正确定义:

.hidden {
    display: none;
}

内容的提问来源于stack exchange,提问作者amiola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:24:50