配送城市地址联动选择JQuery

 记录一次使用jq实现3层地址联动选择流程!效果如图。

 需要引入 jq.js、layer.js、layui.js、layui.css (icon图标)

 

 

二、选中后页面展示效果

 

 

三、页面展示HTML

                   <div  class="content-info">
                                        <p>
                                            <span class="tips-info">!</span>
                                            <span class="miniP">
                                                地区设置:
                                                <span class="child-content">
                                                    <button class="btn btn-primary btn-small" id="address">添加配送地区</button>
                                                </span>
                                            </span>
                                        </p>

                                            <table id="tblRules" style="display: none;">
                                                <thead>
                                                <tr>
                                                    <th>配送地区</th>
                                                    <th>首件数(件)</th>
                                                    <th>首件价格(元)</th>
                                                    <th>续件数(件)</th>
                                                    <th>续件价格(元)</th>
                                                    <th>操作</th>
                                                </tr>
                                                </thead>
                                                <tbody id="tdata">

                                                </tbody>
                                            </table>
                                    </div>

四、Model模态框弹层HTML

deliveryAreaList 是一个数组,数据格式如下:

{
    "华东":{
        "857":{
            "name":"上海市",
            "city":[
                {
                    "id":"867",
                    "city":"上海市",
                    "province_id":857
                }
            ]
        }
    }
}

 

{#选择提示#}
    <div id="prefectureModal"   class="modal stock-modal hide fade" tabindex="-1" style="left: 41%; width: 60%;" role="dialog" aria-labelledby="skuStockInfoModal" role="dialog" aria-labelledby="dialogModal" aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3>选择区域</h3>
        </div>
        <div class="modal-body">
            <div class="dialog-modal-body">
                <div>
                    <ul class="parent-ul">
                        {% for deliveryAreaName, deliveryAreaInfo in deliveryAreaList %}
                            {% if deliveryAreaInfo|length > 0 %}
                                <li class="child-qu">
                                    <div> <label><input type="checkbox" value="{{ deliveryAreaName }}" class="qu-name"> {{ deliveryAreaName }}</label></div>
                                    <ul class="child-ul">
                                    {% for areaId, areaValue in deliveryAreaInfo %}
                                        <li>
                                            <input type="checkbox" id="area{{ areaId }}" class="bigarea" data-id="{{ areaId }}" data-name="{{ areaValue.name }}" value="{{areaId}}">
                                            <label for="area{{ areaId }}" style="display: inherit;" class="area-name">{{ areaValue.name }} </label>
                                            <i class="layui-icon layui-icon-triangle-d city-list" data-province-id="{{areaId}}"></i>
                                            <ul class="city-ul" style="display:none">
                                                {% for id, val in areaValue.city %}
                                                    <li><input type="checkbox" class="bigcity" id="city{{val.id}}"  data-id="{{val.id}}" data-name="{{val.city}}" value="{{val.id}}"> <label for="city{{val.id}}" style="display: inherit;" class="city-name">{{ val.city }} </label>  </li>
                                                {% endfor %}
                                            </ul>
                                        </li>
                                    {% endfor %}
                                    </ul>
                                </li>
                            {% endif %}
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary btn-modal-update-stock saveAddress">保存</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        </div>
    </div>

 五、CSS

       .tab-content{
            list-style: none;
        }
        .tab-content li {
            border: 1px solid #99999978;
            width: 200px;
            text-align: center;
            height: 40px;
            float: left;
            line-height: 40px;
        }
        .tab-content li a {
            text-decoration:none;
            cursor: pointer;
            display:block;
            overflow:hidden;
            line-height: 40px;
            color: #000;
        }
        .actives {
        /* #bcbcbc; */
            background-color: #6aa6ed;
        }
        .tabs-cont {
            padding-top: 20px;
        }
        .cont-page {
            width: 94%;
            margin-bottom: 20px;
        }
        .cont-page .title {
            background-color: #c3d1f5ba;
            height: 34px;
            line-height: 34px;
            padding-left: 25px;
            font-size: small;
            font-weight: bold;
        }
        .cont-page .content {
            background-color: #f2f2f2;
        }
        .con-child {
            padding: 23px 0px 0px 40px;
        }
        .child-content{
            padding-left: 10px;
        }
        .content-info {
            padding-bottom: 15px;
        }
        .tips{
            color: red;
            font-size: small;
        }
        .tips-info {
            color: #f7f2f2;
            width: 11px;
            height: 18px;
            background-color: #ec0b0b;
            cursor: pointer;
            display: -webkit-inline-box;
            border-radius: 23px;
            text-align: center;
            padding-left: 7px;
            font-size: small;
            line-height: 19px;
        }
        .parent-ul .child-qu {
            list-style-type: none;
        }
        ul.child-ul {
            padding-left: 45px;
        }
        .child-ul li {
            list-style-type: none;
            display: inline;
            line-height: 40px;
            padding: 14px;
            position: relative; /*相对定位*/
        }
        .parent-ul {
            padding: 20px 20px 20px 40px;
        }
        input[type="checkbox"] {
            /*/-webkit-appearance: none; !*清除复选框默认样式*!*/
            border: 0.5px solid #627BF6;
            vertical-align: middle;
            width: 15px;
            height: 15px;
            margin-top: -5px;
            margin-right: 0 !important;
            border-radius: 0;
        }
        input[type="checkbox"]:checked {
            /* background-position: -48px 0; */
            background: #627BF6; /*复选框的背景图*/
            background-size: contain;
        }
        .child-qu ul li span, .city-list{
            cursor:pointer
        }
        .activity{
            position: absolute;
            left: 0; /*相对定位*/
            z-index: 2;
            display: none;
            border: 2px solid #CAE4FF;
            background-color: #EDF6FF;
            width: 198px;
            padding: 10px;
        }
        #tblRules{
            text-align: center;
            margin-top: 20px;
            width: 82%;
        }
        #tblRules th{
            height:40px;
            background-color:#6aa6ed;
            border:1px solid #ccc;
        }
        #tblRules td{
            background-color:#fff;
            height:45px;
            min-width:150px;
            border:1px solid #ccc;
            text-align: center;
        }
        .miniP {
            padding-left: 8px;
        }

 

 六、JS (包含了整个页面上的js,具体比较懒没有抽出来)

        var feeList      = {{ feeList | raw }}; 
        var addressInfo  = {{ addressInfo | raw }};
        var id           = null;
        var Request      = GetRequest();
        if ( typeof Request['id'] == 'string' ) {
            id           = Request['id'];
        }

        var _info = {
            main:function () {
                _info.init();
                _info.selectedAddress();    //城市下拉框(控制城市的展示和标签的动态切换)
                _info.quClick();            //选中区触发事件(向下控制省和城市全选)
                _info.bigareaClick();       //选中省的触发事件(向下控制城市全选,向上控制选中区)
                _info.cityClick();          //选中城市的触发事件(控制选中,向上控制选中省)
                _info.deleteData();         //删除临时缓存中的数据
                _info.clearHtml();          //清除弹层选中事件
                _info.saveSelected();       //往缓存中插入选中事件
                _info.checkedAddress = [];  //临时选中缓存
                _info.sendAddressChange();  //发货地址
                _info.cancelAddressChange();//退货地址
                _info.saveTemple();         //保存运费模板
                _info.id                    = id;
                //发货物流地址
                _info.deliveryProvinceId    = 0;
                _info.deliveryCityId        = 0;
                _info.districtId            = 0;
                //退货物流地址
                _info.refundProvinceId      = 0;
                _info.refundCityId          = 0;
                _info.refundDistrictId      = 0;
                //初始化数据
                if ( feeList.length ) {
                    _info.checkedAddress = feeList;
                    _info.reviewHtml(_info.checkedAddress);
                }
                if ( typeof addressInfo == 'object' && _info.id ) {
                    _info.deliveryProvinceId    = addressInfo.delivery.delivery_province_id;
                    _info.deliveryCityId        = addressInfo.delivery.delivery_city_id;
                    _info.districtId            = addressInfo.delivery.delivery_district_id;
                    _info.getCityList( _info.deliveryProvinceId, 1);
                    _info.getCountyList( _info.deliveryCityId, 1);

                    _info.refundProvinceId      = addressInfo.refund.refund_province_id;
                    _info.refundCityId          = addressInfo.refund.refund_city_id;
                    _info.refundDistrictId      = addressInfo.refund.refund_district_id;
                    _info.getCityList(_info.refundProvinceId, 0);
                    _info.getCountyList(_info.refundCityId, 0);
                }
            },
            init:function () {
                //物流公司初始化配置
                $('.demo').fSelect({
                    placeholder: '请选择物流公司',
                    numDisplayed: 10,
                    searchText: '搜索',
                    showSearch: true
                });
                //跳转链接
                $('.cancel').click(function () {
                    window.location.href='/expresstemplate/index';
                });
                //选项卡
                $(document).find('[data-toggle="tooltip"]').tooltip();
                $(".tab-content ul li").click(function(){
                    $(this).addClass("actives").siblings().removeClass("actives");
                });
                //弹出提示
                $(".tips-info").mouseover(function () {
                    layer.tips( '平台规定以下地区必须进行商品配送:北京、上海、深圳、广州', '.tips-info', {
                        tips: [4, '#BAB758'],
                        area: ['190px', 'auto'],
                        time:2000
                    });
                });
                //地区选择文字自动选中checkBox
                $('.child-qu ul li span').click(function () {
                    if ($(this).prev()[0].checked) {
                        $(this).prev('input').prop('checked', false)
                    } else {
                        $(this).prev('input').prop('checked', true)
                    }
                });
                //地址弹层
                $('#address').click(function () {
                    _info.disabledHtml(_info.checkedAddress);
                    $('#prefectureModal').modal('show');
                })
            },
            selectedAddress:function () {
                $('.city-list').click(function () {
                    if ( $(this).parents().children('.city-ul').is(':hidden') ) {
                        //消除所有父级孩子热点
                        $('.parent-ul .child-qu').each(function () {
                            $(this).children().find('.city-ul').removeClass('activity');
                            $(this).children().find('.city-ul').css('display', 'none');
                            $(this).children().find('.city-list').removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');
                        });
                        //开启热点
                        $(this).removeClass('layui-icon-triangle-d').addClass('layui-icon-triangle-r');
                        $(this).parents().children('.city-ul').css('display', 'block');
                        $(this).parents().children('.city-ul').addClass('activity');
                    } else {
                        //关闭热点
                        $(this).removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');
                        $(this).parents().children('.city-ul').css('display', 'none');
                        $(this).parents().children('.city-ul').removeClass('activity');
                    }

                });
            },
            quClick:function () {
                $('.qu-name').click(function () {
                    if ($(this).is(':checked')) {
                        $(this).parents().children('.child-ul').each(function () {
                            $(this).find('.bigarea').prop("checked", true);
                            $(this).children().find('.city-ul').each(function () {
                                $(this).find('.bigcity').prop("checked", true);
                            })
                        })
                    } else {
                        $(this).parents().children('.child-ul').each(function () {
                            $(this).find('.bigarea').prop("checked", false);
                            $(this).children().find('.city-ul').each(function () {
                                $(this).find('.bigcity').prop("checked", false);
                            })
                        })
                    }
                })
            },
            bigareaClick:function() {
                $('.bigarea').click(function () {
                    if ($(this).is(':checked')) {
                        //在小父亲下去找 parents 是大父亲
                        $(this).parent().find('.city-ul').each(function () {
                            $(this).find('.bigcity').prop("checked", true);
                        });
                        //省选中时自动选中区
                        $(this).parent().parent().parent().find('.qu-name').prop('checked', true);

                    } else {
                        $(this).parent().find('.city-ul').each(function () {
                            $(this).find('.bigcity').prop("checked", false);
                        });
                        //省全都取消的时候取消区
                        var checkAreaHasCheck = false;
                        $(this).parent().parent().each(function () {
                            if ($(this).find('.bigarea').is(":checked")) {
                                checkAreaHasCheck = true;
                            }
                        });
                        if ( !checkAreaHasCheck ) {
                            $(this).parent().parent().parent().find('.qu-name').prop('checked', false);
                        }
                    }
                })
            },
            cityClick:function() {
                $('.bigcity').bind('click',function () {
                    if ( $(this).is(':checked') ) {
                        $(this).parent().parent().parent().find('.bigarea').prop("checked", true);
                        $(this).parent().parent().parent().parent().parent().find('.qu-name').prop("checked", true);
                    } else {
                        //一级一级取消【省】市级全都取消的时候取消省
                        var checkCityHasCheck = false;
                        $(this).parent().parent().each(function () {
                            if ($(this).find('.bigcity').is(':checked')) {
                                checkCityHasCheck = true;
                            }
                        });
                        if ( !checkCityHasCheck ) {
                            $(this).parent().parent().parent().find('.bigarea').prop("checked", false);
                        }
                        //一级一级取消【区】市级全都取消的时候取消区
                        var checkQuHasCheck = false;
                        $(this).parent().parent().parent().parent().each(function () {
                            if ($(this).find('.bigarea').is(':checked')) {
                                checkQuHasCheck = true;
                            }
                        });
                        if ( !checkQuHasCheck ) {
                            $(this).parent().parent().parent().parent().parent().find('.qu-name').prop("checked", false);
                        }
                    }

                });
            },
            saveSelected:function () {
                $('.saveAddress').click(function () {
                    var checked = _info.getChecked();

                    //储存表格中的数据
                    if ( $("#tdata tr").length >1 ) {
                        $("#tdata tr").each(function(key, val) {
                            var firstPrice   = $(this).children('td').children('.firstPrice').val();
                            var doublePrice  = $(this).children('td').children('.doublePrice').val();

                            _info.checkedAddress[key].firstPrice  = firstPrice;
                            _info.checkedAddress[key].doublePrice = doublePrice;
                        });
                    }

                    if (_info.checkedAddress.length ) {
                        checked.forEach(function (val, key) {
                            _info.checkedAddress.push(val);
                        })
                    } else {
                        _info.checkedAddress = checked;
                    }
                    $('#prefectureModal').modal('hide');
                    _info.reviewHtml(_info.checkedAddress);
                });
            },
            reviewHtml:function(checked){

                if (checked.length) {
                    $('#tblRules').css('display', 'block');
                    $('#tdata').html('');
                    checked.forEach(function (val, key) {
                        if ( val.city.length ) {
                            var cityList = [];
                            var cityName = '';
                            val.city.forEach(function (v, k) {
                                cityList.push(v.name);
                            });
                             //如果全选就展示省
                            if ( val.province.cityTotal == cityList.length ) {
                                cityName = val.province.name;
                            } else {
                                cityName = cityList.join(',');
                            }

                            var _html = ' <tr>\n' +
                                '       <td>'+ cityName +'</td>\n' +
                                '       <td> <input type="text" value="1" disabled  style="width: 84px;margin: 6px 0px 6px 0px;"> </td>\n' +
                                '       <td> <input type="text" class="firstPrice" disabled value="'+val.firstPrice+'" maxlength="6"  name="firstPrice"   style="width: 84px; margin: 6px 0px 6px 0px;"> </td>\n' +
                                '       <td> <input type="text" value="1" disabled  style="width: 84px;margin: 6px 0px 6px 0px;"> </td>\n' +
                                '       <td> <input type="text" class="doublePrice" disabled value="'+val.doublePrice+'" maxlength="6" name="doublePrice"  style="width: 84px;margin: 6px 0px 6px 0px;"> </td>\n' +
                                '       <td> <a href="javascript:;" style="color: red;" class="deleteData" data-key="'+key+'" data-province="'+ val.province.id +'">删除</a></td>\n' +
                                '     </tr>';
                            $('#tdata').append(_html);
                        }
                    })
                }
            },
            disabledHtml:function(checkedAddress) {
                var ul              = $(".parent-ul");
                ul.each(function (index, a) {
                    //var qu = $(this).children().find(".qu-name");
                    var area = $(this).children().find('.child-ul');
                    area.each(function () {
                        var quSelect = false;
                        $(this).find('li').each(function(){

                            var areaId = $(this).find('.bigarea').attr('data-id');
                            var isSelect = false;
                            checkedAddress.forEach(function (val, key) {
                                if ( val.province.id == areaId ) {
                                    isSelect = true;
                                }
                            });

                            if ( isSelect ) {
                                quSelect = true;
                                $(this).find('.bigarea').prop('checked', true);
                                $(this).find('.bigarea').attr('disabled', 'disabled');
                            } else {
                                $(this).find('.bigarea').prop('checked', false);
                                $(this).find('.bigarea').removeAttr('disabled');
                            }

                            var city = $(this).find('.city-ul');

                            city.each(function () {
                                $(this).find('li').each(function(){
                                    var cityId = $(this).find('.bigcity').attr('data-id');
                                    var isCitySelect = false;
                                    checkedAddress.forEach(function (val, key) {
                                        val.city.forEach(function (v, k) {
                                            if (v.id == cityId) {
                                                isCitySelect = true;
                                            }
                                        });
                                    });

                                    if ( isCitySelect ) {
                                        $(this).find('.bigcity').prop('checked', true);
                                        $(this).find('.bigcity').attr('disabled', 'disabled');
                                    } else if ( !$(this).find('.bigcity').attr('disabled') ) {
                                        $(this).find('.bigcity').prop('checked', false);
                                        $(this).find('.bigcity').removeAttr('disabled');
                                    }

                                })
                            });

                        });
                        if ( quSelect ) {
                            $(this).parent().find(".qu-name").prop('checked', true);
                            $(this).parent().find(".qu-name").attr('disabled', 'disabled');
                        } else {
                            $(this).parent().find(".qu-name").prop('checked', false);
                            $(this).parent().find(".qu-name").removeAttr('disabled');
                        }
                    });

                });
            },
            deleteData:function() {
                //每次删除都将页面上的table表格
                $(document).on('click', '.deleteData', function (e) {
                    e.preventDefault();
                    var delKey      = $(this).attr('data-key');
                    var newAddress  = [];

                    //储存表格中的数据
                    var firstPrice = doublePrice = 0;
                    $("#tdata tr ").each(function(key, val) {
                        firstPrice   = 0;//$(this).children('td').children('.firstPrice').val();
                        doublePrice  = 0;//$(this).children('td').children('.doublePrice').val();
                        _info.checkedAddress[key].firstPrice  = firstPrice;
                        _info.checkedAddress[key].doublePrice = doublePrice;
                    });

                    _info.checkedAddress.forEach(function (val, key) {
                        if (key != delKey) {
                            newAddress.push(_info.checkedAddress[key])
                        }
                    });

                    _info.checkedAddress = newAddress;
                    //如果有数据就重新渲染表格数据
                    if ( _info.checkedAddress.length ) {
                        _info.reviewHtml(_info.checkedAddress);
                    } else {
                        $('#tblRules').css('display', 'none');
                    }
                    //清除弹层选中事件
                    _info.clearHtml();
                })
            },
            clearHtml:function() {
                var ul = $(".parent-ul");
                ul.each(function (index, a) {
                    var qu = $(this).children().find(".qu-name");
                    if (qu.is(':checked')) {
                        qu.prop("checked", false);
                        qu.removeAttr("disabled");
                        var area = $(this).children().find('.child-ul');
                        area.each(function () {
                            $(this).find('li').each(function(){
                                if ($(this).find('.bigarea').is(':checked')) {
                                    $(this).find('.bigarea').prop("checked", false);
                                    $(this).find('.bigarea').removeAttr("disabled");
                                    var city        = $(this).find('.city-ul');
                                    city.each(function () {
                                        $(this).find('li').each(function(){
                                            if ($(this).find('.bigcity').is(':checked')) {
                                                $(this).find('.bigcity').prop("checked", false);
                                                $(this).find('.bigcity').removeAttr("disabled");
                                            }
                                        })
                                    });
                                }
                            });
                        });
                    }
                });
            },
            getChecked:function () {
                var checked         = [];
                var cityList        = [];
                var provinceInfo    = {};
                var ul              = $(".parent-ul");
                ul.each(function (index, a) {
                    var qu = $(this).children().find(".qu-name");
                    if (qu.is(':checked')) {
                        var area = $(this).children().find('.child-ul');
                        area.each(function () {
                            $(this).find('li').each(function(){
                                if ($(this).find('.bigarea').is(':checked')) {
                                    provinceInfo    = {
                                                        'id'  : $(this).find('.bigarea').attr('data-id'),
                                                        'name': $(this).find('.bigarea').attr("data-name"),
                                                        'cityTotal' : 0,
                                                    };
                                    cityList        = [];
                                    var city        = $(this).find('.city-ul');
                                    var cityTotal   = 0;
                                    city.each(function () {
                                        $(this).find('li').each(function(){
                                            ++cityTotal;
                                            if ($(this).find('.bigcity').is(':checked') && !$(this).find('.bigcity').attr('disabled')) {
                                                cityList.push({
                                                    'id'  : $(this).find('.bigcity').attr('data-id'),
                                                    'name': $(this).find('.bigcity').attr("data-name"),
                                                });
                                            }
                                        })
                                    });
                                    provinceInfo.cityTotal = cityTotal;
                                    if ( cityList.length ) {

                                        checked.push({
                                            'province' : provinceInfo,
                                            'city'     : cityList,
                                            'firstPrice': '0.00', //记录输入首件价格
                                            'doublePrice': '0.00', //记录输入续件价格
                                            'firstNum' : 1,
                                            'doubleNum': 1,
                                        });
                                    }
                                }
                            });
                        })
                    }
                });

                return checked;

            },
            sendAddressChange:function () {
                $('#select-province-fa').change(function () {
                    var provinceId =  $('select[name="provinceSend"]').find("option:selected").val();
                    _info.getCityList(provinceId, 1);
                });
                $('#select-city-fa').change(function () {
                    var cityId =  $('select[name="citySend"]').find("option:selected").val();
                    _info.getCountyList(cityId, 1);
                });
            },
            cancelAddressChange:function () {
                $('#select-province-cancel').change(function () {
                    var provinceId =  $('select[name="provinceCancel"]').find("option:selected").val();
                    _info.getCityList(provinceId, 0);
                });
                $('#select-city-cancel').change(function () {
                    var cityId =  $('select[name="cityCancel"]').find("option:selected").val();
                    _info.getCountyList(cityId, 0);
                });
            },
            getCityList:function (provinceId, type) {
                $.ajax({
                    url: "/nation/citylist",
                    type: "GET",
                    async: false,
                    data: {
                        provinceId: provinceId
                    }
                }).done(function(response) {
                    var w = $.parseJSON( response );
                    var html = '<option value="">城市</option>';

                    for( var i = 0; i < w.length; i ++ ) {
                        var cityInfo = w[i];
                        var selected = '';
                        if ( type ) {
                            if( cityInfo.id == _info.deliveryCityId ) {
                                selected = 'selected';
                            }
                        } else {
                            if( cityInfo.id == _info.refundCityId ) {
                                selected = 'selected';
                            }
                        }
                        html += '<option value="' + cityInfo.id + '" '+selected+' >' + cityInfo.city + '</option>';
                    }
                    if ( type ) {
                        $('select#select-city-fa').html( html );
                    } else {
                        $('select#select-city-cancel').html( html );
                    }
                }).fail(function () {
                    return false;
                });
            },
            getCountyList:function (cityId, type) {
                $.ajax({
                    url: "/nation/districtlist",
                    type: "GET",
                    async: false,
                    data: {
                        cityId: cityId
                    }
                }).done(function(response) {
                    var w = $.parseJSON( response );
                    var html = '<option value="">区县</option>';
                    for( var i = 0; i < w.length; i ++ ) {
                        var districtInfo = w[i];
                        var selected = '';
                        if ( type ) {
                            if( districtInfo.id == _info.districtId ) {
                                selected = 'selected';
                            }
                        } else {
                            if( districtInfo.id == _info.refundDistrictId ) {
                                selected = 'selected';
                            }
                        }
                        html += '<option value="' + districtInfo.id + '" '+selected+' >' + districtInfo.district + '</option>';
                    }
                    if ( type ) {
                        $('select#select-district-fa').html( html );
                    } else {
                        $('select#select-district-cancel').html( html );
                    }
                    return false;
                }).fail(function () {
                    return false;
                });
            },
            saveTemple:function () {

                $('.saveTemple').click(function () {
                    
                    /*模版基础信息*/
                    var tplName     = $('input[name="tplName"]').val().trim();//模板名称
                    var tplStatus   = $('select[name="tplStatus"]').find("option:selected").val();//启用1 禁用0
                    if ( !tplName ) {
                        layer.alert('模板名称不能为空', {icon: 0,skin: 'layer-ext-moon'});
                        return false;
                    }

                    /*运费设置-配送地区*/
                    var tplType         = $('input[name="tplType"]').val();//运费类型 按件计费
                    var checkedAddress  = _info.checkedAddress;
                    var deliveryFeeList = [];

                    if ( !checkedAddress.length ) {
                        layer.alert('地区设置不能为空.', {icon: 0,skin: 'layer-ext-moon'});
                        return false;
                    }

                    var priceData  = [];
                    var firstPrice = doublePrice = 0;
                    var priceReg   = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;

                    try {

                        $("#tdata tr ").each(function(){

                            firstPrice   = $(this).children('td').children('.firstPrice').val();
                            doublePrice  = $(this).children('td').children('.doublePrice').val();

                            if ( firstPrice ) {
                                if ( !priceReg.test(firstPrice) ){
                                    throw new Error('请输入正确的运费模板价格,整数或保留两位小数');
                                }
                            } else if (doublePrice)  {
                                if ( !priceReg.test(doublePrice) ){
                                    throw new Error('请输入正确的运费模板价格,整数或保留两位小数');
                                }
                            }

                            firstPrice   = firstPrice ?  parseFloat(firstPrice).toFixed(2) : 0;
                            doublePrice  = doublePrice ?  parseFloat(doublePrice).toFixed(2) : 0;

                            if ( doublePrice*100 > firstPrice*100 ) {
                                throw new Error('地区设置:续件价格不能大于首件价格');
                            }
                            if ( doublePrice> 9999 ||  firstPrice > 9999) {
                                throw new Error('地区设置:首件和续件价格最大不能大于9999元');
                            }

                            priceData.push({
                                'firstPrice' : firstPrice,
                                'doublePrice' : doublePrice,
                            });

                        });
                    } catch (e) {
                        layer.alert(e.message, {icon: 0,skin: 'layer-ext-moon'});
                        throw e
                    }

                    if ( priceData.length ) {
                        checkedAddress.forEach(function (val, key) {
                            var cityIds = [];
                            val.city.forEach(function (v, k) {
                                cityIds.push(v.id)
                            });
                            deliveryFeeList.push({
                                "provinceId": val.province.id,
                                "cityIds": cityIds.join(','),
                                "startNum": 1,
                                "startFee": parseInt( priceData[key]['firstPrice']*100 ),
                                "incrementNum": 1,
                                "incrementFee": parseInt( priceData[key]['doublePrice']*100 ),
                            })
                        });
                    }

                    /*发货地信息*/
                    var deliveryContacter   = $('input[name="deliveryContacter"]').val().trim(); //发货联系人
                    var deliveryProvinceId  = $('select[name="provinceSend"]').find("option:selected").val(); //发货地区-省
                    var deliveryCityId      = $('select[name="citySend"]').find("option:selected").val();
                    var deliveryDistrictId  = $('select[name="districtSend"]').find("option:selected").val();
                    var deliveryDetail      = $('textarea[name="deliveryDetail"]').val().trim(); //发货地区-发货详情地址
                    var deliveryTelZone     = $('input[name="delivery_tel_zone"]').val().trim();//发货地区-座机号码
                    var deliveryTelNumber   = $('input[name="delivery_tel_number"]').val().trim();
                    var deliveryTelExt      = $('input[name="delivery_tel_ext"]').val().trim();
                    var deliveryMobile      = $('input[name="deliveryMobile"]').val().trim(); //发货地区-手机号码
                    var deliveryTel         = '';//发货电话号码,手机电话二选一
                    if ( !deliveryContacter ) {
                        layer.alert('发货联系人必填', {icon: 0,skin: 'layer-ext-moon' });
                        return false;
                    }
                    if ( !deliveryProvinceId ||  !deliveryCityId || !deliveryDistrictId) {
                        layer.alert('发货地区必填', {icon: 0,skin: 'layer-ext-moon'});
                        return false;
                    }
                    if ( !deliveryDetail ) {
                        layer.alert('发货详情必填', {icon: 0,skin: 'layer-ext-moon' });
                        return false;
                    }
                    if ( deliveryTelZone && deliveryTelNumber) {
                        var a = /0\d{2,6}-\d{7,9}/;
                        deliveryTel = deliveryTelZone + '-' + deliveryTelNumber;
                        if ( !a.test(deliveryTel) ) {
                            layer.alert('发货座机号码格式有误,请重填', {icon: 0,skin: 'layer-ext-moon'});
                            return false;
                        }
                        if ( deliveryTelExt ) {
                            deliveryTel += '-' + deliveryTelExt;
                        }
                    }

                    if ( deliveryMobile ) {
                        if(!(/^1[3456789]\d{9}$/.test(deliveryMobile))){
                            layer.alert('发货手机号码格式有误,请重填', {icon: 0,skin: 'layer-ext-moon'});
                            return false;
                        }
                    }

                    if ( !deliveryMobile && !deliveryTel ) {
                        layer.alert('发货电话号码或手机号码必填二选一', { icon: 0, skin: 'layer-ext-moon'});
                        return false;
                    }

                    var ways = [];
                    $('.fs-optgroup>.fs-option').each(function (val, key) {
                        if ( $(this).hasClass('selected') ) {
                            ways.push( $(this).attr('data-value'));
                        }
                    });
                    if ( !ways.length ) {
                        layer.alert('发货快递公司必填', { icon: 0, skin: 'layer-ext-moon'});
                        return false;
                    }
                    var expressWays = ways.join(','); //快递公司

                    /*退货地信息*/
                    var refundContacter   = $('input[name="refundContacter"]').val().trim(); //退货联系人
                    var refundProvinceId  = $('select[name="provinceCancel"]').find("option:selected").val(); //退货地区-省
                    var refundCityId      = $('select[name="cityCancel"]').find("option:selected").val();
                    var refundDistrictId  = $('select[name="districtCancel"]').find("option:selected").val();
                    var refundDetail      = $('textarea[name="refundDetail"]').val().trim(); //退货地区-发货详情地址
                    var refundTelZone     = $('input[name="refund_tel_zone"]').val().trim();//退货地区-座机号码
                    var refundTelNumber   = $('input[name="refund_tel_number"]').val().trim();
                    var refundTelExt      = $('input[name="refund_tel_ext"]').val().trim();
                    var refundMobile      = $('input[name="refundMobile"]').val().trim(); //退货地区-手机号码
                    var refundTel         = '';//发货电话号码,手机电话二选一
                    if ( !refundContacter ) {
                        layer.alert('退货联系人必填', {icon: 0,skin: 'layer-ext-moon' });
                        return false;
                    }
                    if ( !refundProvinceId ||  !refundCityId || !refundDistrictId) {
                        layer.alert('退货地区必填', {icon: 0,skin: 'layer-ext-moon'});
                        return false;
                    }
                    if ( !refundDetail ) {
                        layer.alert('退货详情必填', {icon: 0,skin: 'layer-ext-moon' });
                        return false;
                    }

                    if ( refundTelZone && refundTelNumber) {
                        var a = /0\d{2,6}-\d{7,9}/;
                        refundTel = refundTelZone + '-' + refundTelNumber;
                        if ( !a.test(refundTel) ) {
                            layer.alert('退货座机号码格式有误,请重填', {icon: 0,skin: 'layer-ext-moon'});
                            return false;
                        }
                        if ( refundTelExt ) {
                            refundTel += '-' + refundTelExt;
                        }
                    }

                    if ( refundMobile ) {
                        if(!(/^1[3456789]\d{9}$/.test(refundMobile))){
                            layer.alert('退货手机号码格式有误,请重填', {icon: 0,skin: 'layer-ext-moon'});
                            return false;
                        }
                    }

                    if ( !refundMobile && !refundTel ) {
                        layer.alert('退货电话号码或手机号码必填二选一', { icon: 0, skin: 'layer-ext-moon'});
                        return false;
                    }

                    var params = {
                        id : _info.id,
                        tplName : tplName,
                        tplStatus : tplStatus,
                        deliveryContacter : deliveryContacter,
                        deliveryProvinceId : deliveryProvinceId,
                        deliveryCityId: deliveryCityId,
                        deliveryDistrictId : deliveryDistrictId,
                        deliveryDetail : deliveryDetail,
                        deliveryTel : deliveryTel,
                        deliveryMobile : deliveryMobile,
                        expressWays : expressWays,
                        refundContacter : refundContacter,
                        refundMobile : refundMobile,
                        refundTel : refundTel,
                        refundProvinceId : refundProvinceId,
                        refundCityId : refundCityId,
                        refundDistrictId : refundDistrictId,
                        refundDetail : refundDetail,
                        tplType : tplType,
                        deliveryFeeList : JSON.stringify(deliveryFeeList),
                    };

                    if ( _info.id ) {
                        layer.confirm('对应的商品运费模版将被更新,请确认操作!', {
                            btn: ['操作','取消'] //按钮
                        }, function(key){
                            layer.close(key);
                            _info.saveData(params);
                        }, function(){
                        });
                    } else {
                        _info.saveData(params);
                    }

                });
            },
            saveData:function ( params ) {
                var index = '';
                $.ajax({
                    type: "post",
                    url: "/expresstemplate/save",
                    data: params,
                    dataType: "json",
                    beforeSend:function(){
                        index = parent.layer.load();
                    },
                    success:function(e){
                        if(e.errno==0) {
                            layer.msg('操作成功', {icon: 1});
                            layer.confirm('已操作成功,跳转到列表页面吗?', {
                                btn: ['跳转','留下'] //按钮
                            }, function(){
                                window.location.href='/expresstemplate/index'
                            }, function(){
                            });
                        }else{
                            layer.msg(e.errmsg, {icon: 2});
                            return false;
                        }
                    },
                    complete: function() {
                        layer.close(index);
                    },
                    error:function(){
                        layer.alert('系统错误', { icon: 5, skin: 'layer-ext-moon'});
                    }
                });
            },
        };

        $(function () {
            _info.main();
        });

        //获取url中"?"符后的字串
        function GetRequest() {
            var url = location.search;
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
posted @ 2019-12-18 14:22  清零者  阅读(959)  评论(0编辑  收藏  举报