jquery 提交表单 勾选 多选 筛选等笔记

115 阅读5分钟

html部分
  <button type="button" class="btn btn-sm btn-primary handover-customer-btn" data-toggle="modal" data-target="#handoverCustomers">
                                             <i class="fa fa-exchange" aria-hidden="true"></i>点击按钮
                                         </button>
                                         
                                         
                                         
                                         <div class="modal  handoverCustomers" id="handoverCustomers"  tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg" style="width: 1000px;">
    <div class="modal-content animated bounceInRight" style="margin-top:-25px;">
        <div class="modal-header">
            <button type="button" class="close closeOverCustomer" data-dismiss="modal"><span aria-hidden="true" class="cancel-btn">&times;</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title">标题部分</h4>
        </div>
        <div class="modal-body">
            <div class="hand_over_customer_modal" id="hand_over_customer_modal">
                <form  id="handOverForm"   class="hand-over-form  form form-horizontal" method="POST">
                    <div  class="hand-title"><div class="u116">
                        <p class="hand-p">第一步:请选择多选部分</p>
                        </div>
                    </div>
                    <div  class="form-group" style="height: 300px;overflow: hidden; margin-bottom: 20px; margin: 15px 0px ;">
                         <div style="float: left; width: 49%; border: 1px solid #ccc; height: 100%; padding: 10px;border-radius: 5px;">
                            <div class="allTit">
                                <input type="checkbox" id="selectAllCheckbox"><div>筛选全选部分</div>
                            </div>
                           
                            <div class="borderClass"></div>
                            <input type="text" id="handFilterInput"  class="handFilterInput" placeholder="请输入查询关键字">
                            <!-- <button id="handSearchButton">筛选</button> -->
                            <div id="selectOptions" class="handSelectOptions"> </div>
                        </div>
                        <div style="float: right; width: 49%;border: 1px solid #ccc;height: 100%; padding: 10px;border-radius: 5px;" >
                            <div>筛选多选框勾选右侧展示部分</div>
                            <div class="borderClass"></div>
                            <div id="changeOptions" name="customerIds" >
                            </div>
                        </div>
                    </div>
                    <div  class="hand-title">
                        <div class="u116">
                            <p class="hand-p">第二步:人员</p>
                         </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-12 salesUserSelect" ></div>
                    </div>
                    <div  class="hand-title">
                        <div class="u116  yearu16">
                            <p class="hand-p">第三步:年份</p>
                            <!-- <i class="fa fa-question-circle text-ellipsis" data-toggle="tooltip" data-placement="bottom" style="display:inline-block;font-size:20px;color:#000;vertical-align:text-bottom" title="这是tips提醒方法1"></i> -->
                            <div class="yearPosition">
                                <i class="fa fa-question-circle text-ellipsis" style="display:inline-block;font-size:20px;color:#000;vertical-align:text-bottom"></i>
                                <!-- <span class="wenhao">?</span> -->
                            
                                <div class="tooltip-content">
                                        这是tips提醒2
                                </div>
                            </div>
                          
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-12 yearNianSelect">
                          
                        </div>
                    </div>

                    <div  class="hand-title"><div class="u116">
                        <p class="hand-p">第四步:理由</p>
                        </div></div>
                    <div class="form-group">
                        <div class="col-sm-12  ">
                            <div class="remarkLySelect" style="margin-bottom: 10px;"></div>
                            <textarea    style="display: none;" id="remarkTextRrea"    placeholder="请输入理由" class="form-control noreturn  " rows="3" name="remark" maxlength="500"></textarea>
                        </div>
                    </div>

                </form>
            </div>
        
        </div>
        <div class="modal-footer">
            <div id="background" class="background" style="display:none"></div>
            <div id="progressBar" class="progressBar" style="display:none">数据提交中,请稍等...</div>
            <div class="form-group hand-over-customer" style="margin-top:15px;text-align: center;display:block">
                <button type="button" class="btn btn-white cancel-btn cancel-hand-over-btn" data-dismiss="modal" style="color:#fff;width:90px;background:#CCCCCC ">取消</button>
                <button type="submit" class="btn btn-primary submit-btn  save-hand-over-btn"  id="id-save-hand-over-btn" data-button=".handoverCustomers" data-modal="" data-form=".hand-over-form" style="width:90px;">点击提交</button>
            </div>
        </div>
    </div>
</div>
</div>
                                         
                                         

  // 给定的数组数据格式
  var customerData = [
    // {
    //     "key": "999",
    //     "val": "北京",
    //     "optional_res": 0
    // },
    // {
    //     "key": "101160",
    //     "val": "江苏",
    //     "optional_res": 0
    // },
    // {
    //     "key": "101154",
    //     "val": "上海",
    //     "optional_res": 1
    // },

 
];

// 左侧多选的全量数据
var customerDataLeft = [];
// 右侧列表展示数据
var customerRight = [];
// 左侧关键字和筛选数据
var filteredData =[]
// 部分1
//人
var  salesUser= []

//变更负责人

$(document).ready(function() {


    // 初始化交接客户
    // 获取交接客户的下拉框数据
    
    salesUserFn([])

// 监听 点击 AAA 按钮点击事件
$('.handover-customer-btn').click(function() {

    $.ajax({
        url: '/admin/crm/customer/handover/get', // 接口地址
        type: 'GET', 
        dataType: 'json', // 期望的返回数据类型为 JSON
        complete: function(response) {
            // 请求成功时执行的操作
            console.log('请求成功', response);
            // $('.handoverCustomers').show()
            let data=response.responseJSON
            if(data.error_code==0){
                let resData =  data.result
                console.log('resData',resData)
                if (resData && resData.customer) {
                    let ceshidata= resData.customer
                    customerData=ceshidata
                    customerDataLeft=ceshidata
                    console.log('ceshidata',ceshidata)
              
                    if(ceshidata&&ceshidata.length>0){
                        console.log('ceshidata',ceshidata)
                        var handInputHtml =''
                        $.each(ceshidata, function(index, customer) {
                            handInputHtml+=`<div class=${customer.key}><label class="everylabel"><input  style="margin:0px" class="everyInput"  type="checkbox" value=${customer.key}  ${customer.optional_res === 1 ? '' : 'disabled'}  ></input><div class="everySpan">${customer.val}</div></label></div>`
                        });
                        $('#selectOptions').html(handInputHtml);
                    }

                    selectEvery()
                    selectAllFn()
                      console.log('customerDataLeft',customerDataLeft)
                }
                
                if(resData&&resData.salesUser){
                    salesUser=resData.salesUser
                    salesUserFn(JSON.parse(JSON.stringify(salesUser)))
                }

                yearFn()
            }else {
                $('.handoverCustomers').hide()
                return   swal({
                    title:"提示框",
                    text: data.error_msg,
                    type:"warning",
                    showCancelButton:"true",
                    confirmButtonText:"确定",
                    cancelButtonText:"取消",
                });
             
            }
        },
        error: function(xhr, status, error) {
            // 请求失败时执行的操作
            console.error('请求失败', error);
        }
    });
});


    function selectAllFn(){
          // 全选功能
    $('#selectAllCheckbox').change(function() {
        if ($(this).prop('checked')) {
            // 如果全选被选中,则将所有复选框设置为选中状态
           // 遍历每个复选框,检查 disabled 属性
            $('#selectOptions input[type="checkbox"]').each(function() {
                // 检查 disabled 属性是否为 false,如果是,则选中
                if (!$(this).prop('disabled')) {
                 $(this).prop('checked', true);
                }else {
                    $(this).prop('checked', false);
                }
            }); 
            console.log('customerDataLeft',customerDataLeft)
            // 筛选的不为1的数据。 不置灰的值
            let customerDisData = customerDataLeft.filter(item => item.optional_res === 1);
            console.log('customerDisData',customerDisData)
            //筛选数据如果大于0 则右侧需要更新的数据是筛选数据。否则更新数据是。 左侧非置灰的数据
            let dataToMerge=[]
            if(filteredData && filteredData.length > 0){
                dataToMerge=filteredData
            }else {
                dataToMerge= customerDisData
            }
            //合并数据。是右侧本来的数据。 和左侧选中的数据
            let mergedData = [...customerRight, ...dataToMerge];  
         
            // 合并数据去重
            mergedData = mergedData.filter((item, index, self) =>
                index === self.findIndex((t) => (
                    t.key === item.key
                ))
            );
            customerRight=mergedData
            console.log('customerRight',customerRight)
            // 去重后数据展示在右侧
            displayRight(mergedData);
          // 遍历 customerDataLeft 。如果有筛选数据。则筛选数据选中。如果无筛选数据。则非disabled数据选中
                $.each(customerDataLeft, function(index, leftItem) {
                    const leftKey = leftItem.key;
                    // 初始化复选框状态为 false
                    let isChecked = false;
                    // 遍历 mergedData
                    $.each(mergedData, function(index, mergedItem) {
                        const mergedKey = mergedItem.key;
                        // 比较每一项的 key 是否相等
                        if (leftKey === mergedKey) {
                            // 如果相等,则设置复选框状态为 true
                            isChecked = true;
                            return false; 
                        }
                    });
                    // 找到左侧数据中的相应项,设置复选框状态
                    $('#selectOptions .' + leftKey).find('input[type="checkbox"]').prop('checked', isChecked);
                });

        } else {
            // 如果没有筛选的数据(即 filteredData 为空或未定义),则清空右侧数据  
            let remainingData = filteredData && filteredData.length > 0 ?   
            customerRight.filter(item => !filteredData.some(filteredItem => filteredItem.key === item.key)) : [];  
            console.log('filteredData',filteredData)
            //更新右侧数据 
            customerRight= JSON.parse(JSON.stringify(remainingData))
          displayRight(remainingData);
          // 处理左侧数据
        // 取消 filteredData 中对应的复选框的勾选状态(如果有 filteredData)  
        if (filteredData && filteredData.length > 0) {  
            $.each(filteredData, function(index, filteredItem) {  
                $('#selectOptions .'+filteredItem.key).find('input[type="checkbox"]').prop('checked', false);  
            });  
        } else {
            $('#selectOptions input[type="checkbox"]').prop('checked', false);
            filteredData=[]
        }
       }
    });
    }
  


  

function selectEvery(){
        $('#selectOptions').find('input[type="checkbox"]').on('change', function() {
        // 处理右侧数据展示
            var key = $(this).val();
            var checkboxdata =$(this)
        
            if(checkboxdata.prop('checked')){
                  // 在左侧勾选状态。 右侧数据追加
                  const addIndex = customerDataLeft.find(item => item.key === key); // 查找要删除的元素的索引
                    if(addIndex){
                        customerRight.push(JSON.parse(JSON.stringify(addIndex))); // 将数据追加到 customerRight 数组中
                    }
                   
            }else {
                // 在左侧勾选状态。 右侧数据删除
                const index = customerRight.findIndex(item => item.key === key); // 查找要删除的元素的索引
                if (index !== -1) {
                    customerRight.splice(index, 1); // 从右侧数据中删除指定的元素
                }
            }
            // 更新右侧数据展示
            displayRight(customerRight);
            allCheckedFn()
            
   });
}

// 更新全选复选框状态
    function allCheckedFn(){
        var allChecked = $('#selectOptions input[type="checkbox"]:checked').length;
        var totalCheckboxes = $('#selectOptions input[type="checkbox"]').length;
               
        if (allChecked === totalCheckboxes) {
            $('#selectAllCheckbox').prop('indeterminate', false); // 取消半选中状态
            $('#selectAllCheckbox').prop('checked', true); // 设置全选为选中状态
        } else if (allChecked > 0) {
            $('#selectAllCheckbox').prop('checked', false); // 设置全选为未选中状态
            $('#selectAllCheckbox').prop('indeterminate', true); // 设置为半选中状态
        } else {
            $('#selectAllCheckbox').prop('indeterminate', false); // 取消半选中状态
            $('#selectAllCheckbox').prop('checked', false); // 设置全选为未选中状态
        }
    }
     
    // 点击删除按钮时移除对应数据
    $('#changeOptions').on('click', '.delete-span', function() {
        var deletedData = $(this).prev().text(); // 获取要删除的数据
        var prevClass = $(this).prev().attr('class');
        console.log(deletedData,prevClass)
        const indexRight = customerRight.findIndex(item => item.key === prevClass); // 查找要删除的元素的索引
        console.log('indexRight',indexRight)
        if (indexRight !== -1) {
            customerRight.splice(indexRight, 1); // 从右侧数据中删除指定的元素
            displayRight(customerRight)
            $('#selectOptions .' + prevClass).find('input[type="checkbox"]').prop('checked', false);;
        }
        // 更新复选框状态    
        allCheckedFn()
    });

      // 当手动过滤输入框内容发生变化时触发事件
      $('#handFilterInput').on('input', function() {
        var keyword = $(this).val().trim().toLowerCase(); // 获取搜索关键字并转为小写
        // 如果搜索关键字为空,则将左侧数据设置为全量数据 
        searchButton(keyword)
    });

    // 查询数据的筛选。筛选符合条件的客户主体
    function searchButton(keyword) {
        if (keyword === '') {
            for (var n=0;n<customerDataLeft.length;n++){
                $('#selectOptions .' + customerDataLeft[n].key).show()
            }
            filteredData=[]
        } else {
             filteredData = customerDataLeft.filter(function(item) {
             
                if(item['val'].toLowerCase().includes(keyword)){
                    return item ;
                }
            });
            console.log('filteredData',filteredData)
            // 如果有搜索结果,则展示搜索结果;如果没有搜索结果,则展示全量数据 customerData
            if (filteredData.length > 0) {
                   // 使用一个对象来跟踪应该显示的key  
                    var keysToShow = {};  
                    // 遍历filteredData,记录所有应该显示的key  
                    for (var m = 0; m < filteredData.length; m++) {  
                        keysToShow[filteredData[m].key] = true;  
                    }  
                    // 遍历customerDataLeft,根据keysToShow对象来决定显示或隐藏元素  
                    for (var n = 0; n < customerDataLeft.length; n++) {  
                        var key = customerDataLeft[n].key;  
                        // 如果keysToShow中存在这个key,则显示元素,否则隐藏元素  
                        if (keysToShow[key]) {  
                            $('#selectOptions .' + key).show();  
                        } else {  
                            $('#selectOptions .' + key).hide();
                        }  
                    }  
                    console.log('filteredData', filteredData, 'customerDataLeft', customerDataLeft);
            } else {
                for (var n=0;n<customerDataLeft.length;n++){
                    $('#selectOptions .' + customerDataLeft[n].key).hide()
                }
            }
        }
    }

    

      // 右侧数据重置展示
      function displayRight(data) {
        // 清空右侧展示区域
        // $('#changeOptions').empty();
        var changeOptionsDiv = $('#changeOptions'); 
        changeOptionsDiv.empty();
    
        // 根据 customerRight 数组中的数据显示右侧内容
        for (var i = 0; i < data.length; i++) {
            var val = data[i].val;
            var dataDiv = $('<div>').addClass('rightDiv').append(
                $('<span style="display:inline-block">').text(val).addClass(data[i].key), // 添加类以设置样式
                $('<span>').text('x').addClass('delete-span') // 添加类以设置样式
            );
            changeOptionsDiv.append(dataDiv);
        }
    }
    
    // 2=========================2 人

    function  salesUserFn(salesUser){
        var salesSelect = $('.salesUserSelect');
        salesSelect.empty();
        if(salesUser&&salesUser.length>0){
            var salesText = '<option value="">请选择新的负责人</option>';
            for (var i = 0; i < salesUser.length; i++) {
                salesText += '<option value="' + salesUser[i].key + '">' + salesUser[i].val + '</option>';
            }
            var salesSelect = $('<select  class="form-control inline  saleSelect" name="receiver" required>').html(salesText);
        $('.salesUserSelect').append(salesSelect);
        }else {
            var salesText = '<option value="">请选择新的负责人</option>';
            var salesSelect = $('<select  class="form-control inline saleSelect" name="receiver" required>').html(salesText);
            $('.salesUserSelect').append(salesSelect);
        }
    }

  

//2==========人

//3 年份

  function yearFn(){
    var currentYear = new Date().getFullYear();
    var startYear = 2017;
    // 生成年份数组
    var yeardata = [];
    for (var year = startYear; year <= currentYear; year++) {
        yeardata.push({
            "key": year,
            "val": year + "年"
        });
    }

if(yeardata&&yeardata.length>0){
    
    var yearText = '<option value="" >请选择</option>';
    for (var i = 0; i < yeardata.length; i++) {
        yearText += '<option value="' + yeardata[i].key + '">' + yeardata[i].val + '</option>';
    }
    var yearSelect = $('<select  class="form-control inline" name="year" required>').html(yearText);
        $('.yearNianSelect').html(yearSelect);
        $('.yearNianSelect').find('select[name="year"]').find('option:nth-child(2)').prop('selected',true);
   }else {
    var yearText = '<option value="">请选择</option>';
    var yearSelect = $('<select  class="form-control inline" name="year" required>').html(yearText);
        console.log('yearSelect',yearSelect)       
        $('.yearNianSelect').html(yearSelect);
        $('.yearNianSelect').find('select[name="year"]').find('option:nth-child(2)').prop('selected',true);
  }
  }

// 4=============理由
var remarkdata  = [
    {
        "key": 1,
        "val": "人员"
    },
    {
        "key": 2,
        "val": "数据2"
    },
    {
        "key": 3,
        "val": "其他"
    },
    ]
    
    if(remarkdata&&remarkdata.length>0){
        
        var remarkText = '<option value="" >请选择</option>';
        for (var i = 0; i < remarkdata.length; i++) {
            remarkText += '<option value="' + remarkdata[i].key + '">' + remarkdata[i].val + '</option>';
        }
        var remarkSelect = $('<select  class="form-control inline" name="remarks" required>').html(remarkText);
    
            console.log('remarkSelect',remarkSelect)       
            $('.remarkLySelect').append(remarkSelect);
       }else {
        var remarkText = '<option value="" >请选择</option>';
        var remarkSelect = $('<select  class="form-control inline" name="remarks" required>').html(remarkText);
    
            console.log('remarkSelect',remarkSelect)       
            $('.remarkLySelect').append(remarkSelect);
      }

      // 监听 备注的内容。 如果是其他。就展示自己输入。否则。获取当前值
      $('.remarkLySelect').on('change', 'select[name="remarks"]', function() {
        var selectedVal = $(this).val();
        if (selectedVal === '3') {
            $('textarea[name="remark"]').show().addClass('required')
        } else {
            $('textarea[name="remark"]').hide().val('').removeClass('required')
        }
    });

// 4================ 变更理由
  

function  clearHandOverForm (){
        // 清空表单中所有勾选的值
        $('.hand-over-form input[type="checkbox"]').prop('checked', false);
        $('.hand-over-form input[type="text"]').val('');
        $('.hand-over-form textarea').val('');
        $('.hand-over-form select').val('');
        $('.hand-over-form .yearNianSelect select[name="year"]').val(2017);
        $('textarea[name="remark"]').hide()

        customerDataLeft=[]
        filteredData=[]
        customerRight=[]
        displayRight([])
          $('.save-hand-over-btn').prop('disabled', false).css({
                'background-color':'#18a689',
                'border-color': '#18a689'
            });
}
// 点击取消

$('.cancel-hand-over-btn').click(function() {
    // 关闭弹窗 // 恢复初始化
    clearHandOverForm()

});


// 监听模态框关闭事件
$('#handoverCustomers').on('hidden.bs.modal', function () {
    clearHandOverForm()
});

// 点击关闭按钮也清空表单内容
$('.closeOverCustomer').on('click', function() {
    clearHandOverForm()
});




$(".hand-over-form").validate({
    rules: {
        receiver: {
            required: true,
        },
        year:{
            required: true,
        },
        remarks:{
            required: true,
        },
        // remark:{
        //     required: true,
        // }
    },
    messages:{
        receiver: {
         required:"人员为必填项,请完善信息!"
        },
        year: {
            required:"起始年份为必填项,请完善信息!"
       },
       remarks: {
        required:"理由为必填项,请完善信息!"
        },
        // remark: {
        //     required:"理由为必填项,请完善信息!"
        // },
   
    }
})
    // 点击发起审批按钮
    $('.save-hand-over-btn').click(function() {
        // 点击按钮后首先禁用按钮
            $('.save-hand-over-btn').prop('disabled', true).css({
                'background-color': '#cccccc',
                'border-color': '#cccccc'
            })

        if($(".hand-over-form").valid()){
            console.log(' // 如果校验通过')
                 var formData = {};
                 $('.hand-over-form').serializeArray().forEach(function(item) {
                     formData[item.name] = item.value;
                 });
                 // 获取右侧数据的所有key
                 let customerIdsFilter = customerRight.map(item => item.key);
                 let objSubmit = {
                    customerIds:[],
                    receiver:formData.receiver,
                    year:formData.year,
                    remarks:''
                 }
                 //拦截交接客户不能为空为必选项
                 if(customerIdsFilter.length==0){
                    return  swal({
                        title:"提示框",
                        text:'交接客户主体为必填项,请完善信息!',
                        type:"warning",
                        showCancelButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                    },function(isConfirm){
                       
                        if(isConfirm){
                        }else {
                            console.log('取消了吗')
                          
                        }

                        $('.save-hand-over-btn').prop('disabled', false).css({
                            'background-color':'#18a689',
                            'border-color': '#18a689'
                        });
                        
                    });
                 }else {
                    objSubmit.customerIds=customerIdsFilter
                 }

                 // 判断是否为其他。其他将输入理由替换选择理由
                 if(formData.remarks==3){
                    objSubmit.remarks=formData.remark
                 }else {
                    remarkdata.map((item) => {
                        if (item.key == formData.remarks) {
                            objSubmit.remarks = item.val;
                        }
                        return objSubmit;
                    })
                 }
            // 交接接口
                 saveHandOverCheck(objSubmit)

        }else {
            $('.save-hand-over-btn').prop('disabled', false).css({
                'background-color':'#18a689',
                'border-color': '#18a689'
            });
        }
     

    });

    



    //  客户交接-检测提交数据
    function saveHandOverCheck (data){
        console.log('校验datadata',data)
        let subdata=data
      
        $.ajax({
            url: '/admin/crm/customer/handover/check', // 接口地址
            type: 'POST', 
            data:data,
            dataType: 'json', 
            complete: function(response) {
                // 请求成功时执行的操作
                let data= response.responseJSON
                if(data.error_code==0){
                    if( data.result.remind_msg!=''){
                        swal({
                            title: "提示框",
                            text: data.result.remind_msg,
                            type: "warning",
                            showCancelButton: true,
                            allowOutsideClick :false,
                            confirmButtonColor: "#1ab394",
                            confirmButtonText: "是",
                            cancelButtonText:"否",
                            closeOnConfirm: true,
                        },function(isConfirm){
                            if(isConfirm){
                               
                            $('.save-hand-over-btn').prop('disabled', false).css({
                                    'background-color':'#18a689',
                                    'border-color': '#18a689'
                                });
                            }else {
                                HandOverSubmit(subdata)
                            }
                            
                        })
                    }else {
                        HandOverSubmit(subdata)
                    }
                }else {
                    $('.save-hand-over-btn').prop('disabled', false).css({
                        'background-color':'#18a689',
                        'border-color': '#18a689'
                    });
                    return   swal({
                        title:"提示框",
                        text: data.error_msg,
                        type:"warning",
                        showCancelButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                    });
                }
                
            },
            error: function(xhr, status, error) {
                console.error('请求失败', error);
            }
        });
    }

  });


// 提交接口参数
  function HandOverSubmit(subdata){
    $.ajax({
        url: '/admin/crm/customer/handover/submit',
        type: 'POST',
        data: subdata,
        dataType: 'json',
        complete: function(response){
        
            var data = JSON.parse(response.responseText);
            if (data.error_code === 0) {
                window.location.href = '/admin/work/check/list?tab=2';
                clearHandOverForm()
            } else if (data.error_code === 200) {
                location.reload();
            } else {
                setTimeout(function () {
                    swal({
                        title: "提示框",
                        text: data.error_msg,
                        type: "warning",
                        showCancelButton: "true",
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                    });
                }, 100);
            }
        }
    })
  }