zoukankan      html  css  js  c++  java
  • form表单中有bootstrap-switch时怎么提交表单

    由于有bootstrapSwitch开关控件是一个checkbox,就会导致在提交表单时如果没有被选中(开关打开),则向后台提交时会缺失该input对应的参数。

    解决方法:

      在开关的input标签下方增加一个hidden的input标签。初始化开关时默认打开,将hidden的input设置为disabled。如果切换为关闭,则将hidden的input中value属性值设置为2,同时取消disabled属性。

    前端HTML代码

    <div class="form-group">
        <label for="firstname" class="col-sm-3 control-label">是否空闲</label>
        <div class="col-sm-7">
            {#  为了解决checkbox不选中时不会传递该参数,每一个checkbox配一个hidden,当checkbox没选择时,设置hidden的值;当checkbox选择时,disable那个hidden #}
            <input type="checkbox" class="form-control" id="status" name="status" checked value="1">
            <input type="hidden" class="form-control" id="status2" name="status" disabled="disabled">
        </div>
    </div>

    注意:两个input的id值不一样

    js代码

        // 新增时设置状态开关按钮样式
        $("#status").bootstrapSwitch({
            onText: "启用",      // 设置ON文本  
            offText: "禁用",    // 设置OFF文本  
            onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)  
            offColor: "danger",  // 设置OFF文本颜色 (info/success/warning/danger/primary)  
            size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
            onSwitchChange: function (event, state) {
                console.log(event, state)
                //监听switch change事件,可以根据状态把相应的业务逻辑代码写在这里
                let status2Obj = document.getElementById("status2")
                if (state == true) {
                    // 如果开关打开,则将隐藏的input设置为失效
                    status2Obj.setAttribute("disabled", "disabled")
                    // 给checkbox的input框value值设为1
                    $(this).val("1");
                } else {
                    // 如果开关为关闭状态,checkbox为非选中状态,此时序列化form表单时缺少input对应的参数,所以要设置隐藏的的input属性
                    // 设置type="hidden"的input标签的value="2",用来向后端传递
                    status2Obj.setAttribute("value", "2")
                    // 移除disabled属性,否则该input不可用,即不能向后端传递参数
                    status2Obj.removeAttribute("disabled")
                }
            }
        });
  • 相关阅读:
    unix网络编程源码编译问题
    ubuntu15.04下安装docker
    hexo博客的相关配置
    hexo的jacman主题配置
    使用github和hexo搭建静态博客
    操作系统简单认识
    github for windows安装以及教程
    编译原理第五单元习题
    python3入门之列表和元组
    Python3入门之软件安装
  • 原文地址:https://www.cnblogs.com/gcgc/p/13937246.html
Copyright © 2011-2022 走看看