• 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")
                }
            }
        });
  • 相关阅读:
    矩阵——矩阵介绍
    CentOS6.6x86_64 部署 Nginx1.62+MySQL5.6.20+PHP5.6.4
    Linux Stu
    Linux Tips
    网页嵌入百度地图和使用百度地图api自定义地图的详细步骤
    商务通被视频覆盖
    酷炫的响应式导航栏
    织梦DeDeCms列表分页和内容页分页错位解决办法
    form表单中method的get和post区别
    PC端手机访问跳转手机站点
  • 原文地址:https://www.cnblogs.com/gcgc/p/13937246.html
Copyright © 2020-2023  润新知