javascript - 根据 'more detail' 字段对有条件启用的 'parent' 表单字段进行分组的优雅方法

标签 javascript jquery html forms

我正在开发具有许多字段组的大型表单。每个组都有一个“主”真/假下拉/单选按钮字段,设置为 true 后将启用组中关联的“更多详细信息”字段。

我知道执行此操作的常用方法是将更改处理程序上的 JS 绑定(bind)到每个组的“主”字段,然后根据“主”字段的值启用/禁用“更多详细信息”字段

由于这些组有很多,手动将事件处理程序绑定(bind)到每个“主”字段似乎既耗时又重复。当然有更好的方法。如何优雅地实现这个功能呢?想象一下 data-option 属性可以有效地用于此目的。

我的伪代码:

- On change event handler for all fields with data-group-parent
    - For all elements with data-group-child-of == this data-group-parent, set enabled value to 

还有其他建议吗?

最佳答案

这实际上完全取决于您想要如何构建它以及您想要如何驱动它......

如果您只是隐藏或禁用表单的大部分内容,直到其主开关被抛出,那么您就可以节省大量工作。

<form id="MyForm">
    <section>
        <header>
            <p>I would like to experience the best yams the world has to offer!</p>
            <select data-switch="gourmet-yams-of-the-world">
                <option value="1">true</option>
                <option value="0">false</option>
            </select>
        </header>
        <div class="big-ol-list-of-yam-options"
             data-controller="gourmet-yams-of-the-world"
             hidden>
            <!-- ... -->
        </div>
    </section>
</form>

这里你真正缺少的是一个事件监听器、几行属性解析和一些 querySelector 魔法。

// listen for onchange, check if it's a "switch" that changed, and find the panel the switch controls

var isSwitch = function (el) { return el.hasAttribute("data-switch"); },
    getGroupName = function (el) { return el.getAttribute("data-switch"); },
    getGroup = function (root, groupName) {
        return root.querySelector("[data-controller=\"" + groupName + "\"]");
    },
    handleSwitch = function (evt) {
        var el = evt.target,
            switchEl = isSwitch(el),
            groupName, group, action;

        if (!switchEl) { return; }
        groupName = getGroupName(el);
        group = getGroup(MyForm, groupName);
        action = !!(+el.value); // converting it to a number (1 or 0, and then to Boolean)
        toggleGroup(group, action);
    };


MyForm.addEventListener("change", handleSwitch);

请注意,这不能保证适用于所有浏览器。 有趣的是,不支持 addEventListener 的浏览器也很难冒泡“change”事件。

还有其他方法可以做到这一点。

就个人而言,我可能会使用此类事件处理的组合,但使用 JSON 元数据构建实际表单......只是因为。

不是世界上绝对最奇特的解决方案,如果您使用 ghettoIE,则不能保证可以工作(尽管我猜,一点 jQuery 可以有所帮助),并且不是配置驱动的 - 您最终仍然会构建它HTML 无论您目前正在做什么,但为了避免到处都有数百个听众的挫败感,与替代方案相比,这将是一个简单、快速的解决方案。

关于javascript - 根据 'more detail' 字段对有条件启用的 'parent' 表单字段进行分组的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034632/

相关文章:

javascript - 在html中的input中输入索引值时如何显示数组项

javascript - 从移动浏览器上的 Web 应用程序自动调用电话号码

javascript - 我的 IE9 没有尾随逗号,用户的 IE9 不行;为什么?

javascript - jquery从多个中获取当前选定的值

javascript - 文件上传不起作用,但在 Codepen 中正常

html - 将聊天箭头从左侧移动到右侧

javascript - 如何在日期范围选择器中仅显示时间选择器

html - 奇怪的高度与 div 框

html - 如何为 Outlook 网络邮件应用条件内容

javascript - 切换大小写字符串正则表达式和数字