在动态创建的表单后 ajax 调用中将默认值设置为日期选择器

Posted

技术标签:

【中文标题】在动态创建的表单后 ajax 调用中将默认值设置为日期选择器【英文标题】:set default value to date picker at dynamic created form post ajax call 【发布时间】:2018-08-12 20:00:59 【问题描述】:

你好朋友,我在 Angular js 工作,我在 ajax 后调用中返回数据,我从中生成一个表单,在表单内部我有两个输入字段,我用作 datepickcker

我需要为这个日期选择器设置默认值,我尝试了各种方法,但它不起作用 我在我的控制器代码下面发布,请有人帮忙。

控制器

function soListCtrl($scope, DTOptionsBuilder, DTColumnBuilder, $http,
    $templateCache, $q) 
    var data = 
        "active": [0, 1]
    ;

    agentListJSON = ajaxPost(data, "findAllUsersByType").data;

    var vm = this;
    soPermissions();
    vm.dtOptions = DTOptionsBuilder
        .fromFnPromise(
            function () 
                var dataToSelectSo = 
                var nftParentNo = ""
                $(".processingAlert").show();
                var nftParentNo = localStorage.getItem("nftParentNo");
                if (nftParentNo != null) 
                    if (nftParentNo.indexOf('SO') !== -1) 
                        dataToSelectSo = 
                            "soNo": nftParentNo
                        ;
                    
                 else 

                    dataToSelectSo = 
                        "isArchiveList": [1, 11],
                        "allOrOwn": viewSo,
                    ;
                    if (isAgentUsr) 
                        dataToSelectSo.isArchiveList = [1, 3, 11]
                        dataToSelectSo.agentIdList = [parseInt($(
                            "#userId").val())]

                    
                
                return $http(
                        method: 'POST',
                        url: 'getSoAllDetails',

                        data: dataToSelectSo,
                        headers: 
                            'Accept': 'application/json;charset=UTF-8',
                            'Content-Type': 'application/json;charset=UTF-8'
                        
                    )
                    .then(
                        function (response) 
                            $scope.status = response.status;
                            $scope.data = response.data;
                            $scope.salesOrdersJSONList = response.data.data.salesOrdersJSON;
                            if ($scope.salesOrdersJSONList == null) 
                                $scope.salesOrdersJSONList = []
                            
                            $(".processingAlert").hide();
                            var deferred = $q.defer();
                            deferred
                                .resolve($scope.salesOrdersJSONList);
                            localStorage
                                .removeItem("nftParentNo");
                            return deferred.promise;
                        ,
                        function (response) 
                            $scope.data = response.data ||
                                "Request failed";
                            $scope.status = response.status;

                        );

            )
        .withFixedHeader(
            bottom: true
        )
        .withPaginationType('full_numbers')
        .withDataProp('salesOrdersJSONList')
        .withOption('order', [0, 'desc'])
        .withOption('rowCallback', rowCallback)
        .withOption(
            'drawCallback',
            function (settings) 
                if (count < 1) 
                    // onchange='selectStatus1()' onchange="SOByAgent()"

                    $("div.toolbarSO")
                        .html(
                            " <div class='row'> " +
                            "   <div class='col-md-2' >" +
                            "      <div class='form-group'>" +
                            "        <label>Filter:&nbsp;</label>" +
                            "            <select id='fl_status' data-placeholder='Select Status' class='chosen-select form-control'  >" +
                            "              <option value=0></option>" +
                            "              <option value=0>All</option>" +
                            "              <option value='active'>Active</option>" +
                            "              <option value='Unactive'>Unactive</option>" +
                            "              <option value=1>New</option>" +
                            "              <option value=11>In Process</option>" +
                            "              <option value=3>Completed</option>" +
                            "              <option value=18>Archived</option>" +
                            "             <option value='cart'>Cart</option>" +
                            "            </select>" +
                            "       </div>" +
                            "    </div>" +
                            "     <div class='col-md-2'>" +
                            "         <div class='form-group'>" +
                            "          <label>Agent:</label>" +
                            "            <div id='agentListSO'>" +
                            "            </div>" +
                            "         </div>" +
                            "     </div>" +
                            "     <div class='col-md-3'>" +
                            "          <div class='form-group'>" +
                            "            <label>From</label>" +
                            "             <div class='input-daterange input-group' id='datepicker'>" +
                            "                <input type='text' class='form-control' name='start' id='fromallSoDt'/>" +
                            "                  <span class='input-group-addon'>To</span>" +
                            "                  <input type='text' class='form-control' name='end' id='toSoDate'/>" +
                            "             </div>" +
                            "          </div>" +
                            "         </div>" +
                            "     <div class='col-md-3'>" +
                            "    <div class='form-group' style='margin-top:20px'>" +
                            "        <button class='btn btn-info' onClick='getDateWiseSoDetail()'>Submit</button>" +
                            "        <span style='padding-left:10px'>" +
                            "        <button class='btn btn-primary btn-labeled fa fa-refresh' onClick='reserallSO()' id='btn_restSo'>Reset All</button>" +
                            "        </span> " +
                            "          </div>" +
                            " </div>" +
                            " </div>" +
                            "");
                    agentListSO.innerHTML = "";
                    agentListSO.innerHTML = agentListSO.innerHTML +
                        '<select id="ddlagentSO" data-placeholder="Select Agent" class="chosen-select form-control" value="" >';
                    $("#ddlagentSO")
                        .append(
                            '<option class="active-result" value="">' +
                            '</option>' +
                            '<option class="active-result" value="">All' +
                            '</option>');
                    for (var key in agentListJSON.agent) 
                        $("#ddlagentSO").append(
                            '<option class="active-result" value=' +
                            agentListJSON.agent[key].id +
                            '>' +
                            agentListJSON.agent[key].name +
                            '</option>');
                        agentArr.push(agentListJSON.agent[key].id)
                    
                    $('.chosen-select').chosen();
                    $("#fl_status").val("active").trigger(
                        "chosen:updated");
                    if (isAgentUsr) 
                        $("div.toolbarSO").addClass("hide");
                    
                


                var pre = new Date();
                var newd = new Date(pre.setMonth(pre.getMonth() - 3));
                var ddd = newd.getDate();
                var mmm = newd.getMonth() + 1; // January is 0!
                var yyyyy = newd.getFullYear();

                if (ddd < 10) 
                    ddd = '0' + ddd
                

                if (mmm < 10) 
                    mmm = '0' + mmm
                

                var td = mmm + '/' + ddd + '/' + yyyyy;

                var pre = td;

                document.getElementById('fromallSoDt').value = formatDate(
                        new Date(getDateFromFormat(td, "mm/dd/yyyy")),
                        "dd MMM, yy");



                $('#fromallSoDt').datepicker(

                    autoclose: true,
                    format: "dd M, yy"
                );










                debugger
                document.getElementById('toSoDate').value = formatDate(
                        new Date(getDateFromFormat(today, "mm/dd/y")),
                        "dd MMM, yy"); 

                $('#toSoDate').datepicker(
                    autoclose: true,
                    format: "dd M, yy"

                );
                // alert(localStorage.getItem("nftParentNo"))
                if (localStorage.getItem("nftParentNo")) 
                    // alert(localStorage.getItem("nftParentNo"));
                    var salesTable1 = $('#salesOrd').DataTable()
                    // salesTable1.search(localStorage.getItem("nftParentNo"));
                
                count++;
                // alert(JSON.stringify(settings.aoData))
                // console.log(settings.aoData);
                $('[data-toggle="tooltip"]').tooltip();
                $('.srate').raty(
                    readOnly: true,
                    cancel: false,
                    half: true,
                    starType: 'i',
                    score: function () 
                        return $(this).attr('data-score');
                    
                );
                // nft
                /*
                 * if(messageObj.hasOwnProperty('nftType')) if
                 * (messageObj.nftType = "cntByModule")  // var //
                 * cntByGpByMpListModuleWise=messageObj.cntByGpByMpList;
                 * moduleWiseNft(cntByGpByMpListModuleWise)  
                 */
                bySubmodule()
                /*
                 * var b=$('#salesOrd') .DataTable() var
                 * a=b.columns().data();
                 */
                if ($('#salesOrd').DataTable().column(6, 
                        filter: 'applied'
                    ).data().length == 0) 
                    document.getElementById('soTotal').textContent = "0/0.00"
                    document.getElementById('soPengPer').textContent = "0%"

                 else 

                    var pendingAmt = $('#salesOrd').DataTable().column(
                        9, 
                            filter: 'applied'
                        ).data().reduce(function (a, b) 
                        return a + b;
                    )
                    var sum = $('#salesOrd').DataTable().column(6, 
                        filter: 'applied'
                    ).data().reduce(function (a, b) 
                        return a + b;
                    )
                    var pendingPer = (pendingAmt / sum) * 100;
                    document.getElementById('soPengPer').textContent = "(" +
                        Math.round(pendingPer) + "%)";
                    document.getElementById('soTotal').textContent = formateAmount(Math
                            .round(pendingAmt)) +
                        "/ " + formateAmount(Math.round(sum));
                


            )
        .withOption('scrollX', true)
        .withDOM(
            "<'toolbarSO'><'clearfix'><'top'<f><'mar-lft pull-left bottom'i><'mar-lft pull-right bottom'l><'pull-right'p>>rt<'bottom'ipB>")
        .withFixedHeader(
            bottom: true
        );
    vm.dtColumns = [
        DTColumnBuilder
        .newColumn('salesOrders.salesOrderNo')
        .withTitle('SalesOrder No')
        .renderWith(
            function (data, type, full, meta) 
                var status;
                var labelForStatus;
                if (full.length === 0) 
                    return "";
                 else 

                    if (full.salesOrders.isArchived == 1) 
                        var cl = "text-success";
                        labelForStatus = "label label-success";
                        status = "New";
                     else if (full.salesOrders.isArchived == 18) 
                        var cl = "text-warning";
                        status = "Archived";
                     else if (full.salesOrders.isArchived == 11) 
                        var cl = "text-faintyellow";
                        status = "In Process";
                     else if (full.salesOrders.isArchived == 3) 
                        var cl = "text-primary";
                        status = "WO Completed";
                     else 
                        var cl = "text-info";
                    
                    var soC = "";
                    if (isCmtsSo == true) 
                        cmtBtnHtml(data, "commentingSO");
                        soC = cmtBtnHtml(data, "commentingSO");
                    
                    if (isAgentUsr) 
                        return '<div class="row"  style="min-width:222px"><div class="col-md-1" style="padding-top:10px"><span class=" icon-wrap icon-circle ' +
                            cl +
                            '" data-toggle="tooltip" data-placement="right" title="' +
                            status +
                            '"><i class="fa fa-circle"></i></span></div><p class="description col-md-5 pad-top"><strong>' +
                            data + '</strong></d>'; +
                        '</div>';;
                     else if (full.salesOrders.isArchived == 18) 

                        return '<div class="row"  style="min-width:222px"><div class="col-md-1" style="padding-top:10px"><span class=" icon-wrap icon-circle ' +
                            cl +
                            '" data-toggle="tooltip" data-placement="right" title="' +
                            status +
                            '"><i class="fa fa-circle"></i></span></div><p class="description col-md-5 pad-top"><strong>' +
                            data +
                            '</strong></d>' +
                            nftSignal(data, "notyClassSo") +
                            '</div>' +
                            '</br><div class="btn-group">' +
                            doableSo +
                            deleteSo + printSo + '</div>';

                     else if (formateAmount(Math
                            .round((full.salesOrders.totalNetAmt - full.otherSODetailsMap.completedAmt))) == 0.00) 
                        return '<div class="row" style="min-width:222px"><div class="col-md-1" style="padding-top:10px"><span class="icon-wrap icon-circle ' +
                            cl +
                            '" data-toggle="tooltip" data-placement="right" title="' +
                            status +
                            '"><i class="fa fa-circle"></i></span></div><p class="description col-md-5 pad-top"><strong>' +
                            data +
                            '</strong></d>' +
                            nftSignal(data, 'notyClassSo') +
                            '</div>' +
                            '</br><div class="btn-group">' +
                            '<a href="#"  data-toggle="modal" data-target="#archiveSO" class="btn mar-smAll btn-sm btn-default archiveSO " id="archive"><i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Cancel/Archive"></i></a>' +
                            soC + printSo + '</div>';
                     else 
                        return '<div class="row"   style="min-width:222px"><div class="col-md-1" style="padding-top:10px"><span class="icon-wrap icon-circle ' +
                            cl +
                            '" data-toggle="tooltip" data-placement="right" title="' +
                            status +
                            '"><i class="fa fa-circle"></i></span></div><p class="description col-md-5 pad-top"><strong>' +
                            data +
                            '</strong></d>' +
                            nftSignal(data, "notyClassSo") +
                            '</div>' +
                            '</br><div class="btn-group ">' +
                            doableSo +
                            '<a href="#"  data-toggle="modal" data-target="#archiveSO" class="btn mar-smAll btn-sm btn-default archiveSO" id="archive"><i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Cancel/Archive"></i></a>' +
                            soC + printSo + '</div>';
                    
                
            ),
        DTColumnBuilder
        .newColumn('salesOrders.dueDate')
        .withTitle('Due Date')
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    if (data == null || data.length === 0 ||
                        data === '') 
                        return setDueDtHTML;
                     else 
                        return '<p id="dd">' +
                            formatDate(new Date(
                                    getDateFromFormat(data,
                                        "y-MM-dd")),
                                "dd-MMM-y") +
                            '</p>' +
                            '<small> (' +
                            getRemaining(formatDate(
                                new Date(
                                    getDateFromFormat(
                                        data,
                                        "y-MM-dd")),
                                "MM/dd/y")) +
                            ')</small>'
                    
                
            ),
        DTColumnBuilder.newColumn('salesOrders.orderDate').withTitle(
            'Order Date').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    if (data == null || data.length === 0 ||
                        data === '') 
                        return "";
                     else 
                        return formatDate(
                            new Date(getDateFromFormat(
                                full.salesOrders.orderDate,
                                "y-MM-dd")), "dd-MMM-y");

                    
                
            ),
        DTColumnBuilder
        .newColumn('salesOrders.orderDate')
        .withTitle('Age (days)')
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    if (data == null || data.length === 0 ||
                        data === '') 
                        return "";
                     else 

                        return '<p>' +
                            getAge(formatDate(
                                new Date(
                                    getDateFromFormat(
                                        full.salesOrders.orderDate,
                                        "y-MM-dd")),
                                "MM/dd/y")) + '</p>';
                    
                
            ),
        DTColumnBuilder
        .newColumn('customerDetailsMap.name')
        .withTitle('Customer Name')
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else if (isAgentUsr) 
                    return '<a href="#" data-toggle="modal" data-target="#customer" class="customerDetails">' +
                        data + '</a>' + '</br>';
                 else 
                    return '<a href="#" data-toggle="modal" data-target="#customer" class="customerDetails">' +
                        data +
                        '</a>' +
                        '</br><div id="srate" class="srate pad-top" data-score="' +
                        full.customerDetailsMap.rating +
                        '"></div>';
                
            ),
        DTColumnBuilder.newColumn('salesOrders.description').withTitle(
            'Instruction').renderWith(function (data, type, full, meta) 
            if (full.length === 0) 
                return "";
             else 
                if (data == null || data === 0 || data === '') 
                    return updateInstSo;
                 else 
                    return '<p>' + data + '</d><br><br>' + updateInstSo;
                
            
        ),
        DTColumnBuilder
        .newColumn('otherSODetailsMap.discountAmt')
        .withTitle('Total')
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<a href="#" data-toggle="modal" data-target="#pend" class="salesDetail">' +
                        formateAmount(Math.round(data)) +
                        '</a>';
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.qtySum').withTitle(
            'Total Qty').renderWith(function (data, type, full, meta) 
            if (full.length === 0) 
                return "";
             else 
                return data;
            
        ),
        DTColumnBuilder.newColumn('otherSODetailsMap.discCompletedAmt')
        .withTitle('Completed').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<p class="description">' +
                        formateAmount(Math.round(data)) +
                        '</p>';
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.discPendAmt')
        .withTitle('Pend Amt').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return formateAmount(Math.round(data));
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.pendingQtysum')
        .withTitle('Pend Qty').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 

                    return data;
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.pendAmtPer')
        .withTitle('Pend %').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<p href="#">' + Math.round(data) +
                        '%';
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.doableQtySum')
        .withTitle('Doable Qty').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<p>' + data + '</p>';
                
            ),
        DTColumnBuilder
        .newColumn('otherSODetailsMap.doableAmt')
        .withTitle('Doable Amt')
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 

                    if ((full.salesOrders.totalNetAmt -
                            full.otherSODetailsMap.completedAmt == 0) || full.salesOrders.isArchived == 18) 
                        return data;
                     else 
                        return formateAmount(Math.round(data)) +
                            '</br><a href=""  data-type="text" data-pk="1" class="allWo11"> </br>' +
                            'All' + '</a>' + ' | ' +
                            chooseSO;
                    
                
            ),
        DTColumnBuilder.newColumn('otherSODetailsMap.doable').withTitle(
            'Doable %').renderWith(function (data, type, full, meta) 
            if (full.length === 0) 
                return "";
             else 
                // alert(data);'<p>'+formateAmount(data)+'</br>(0.00)</p>'+
                return data;
            
        ),
        DTColumnBuilder.newColumn('customerDetailsMap.createdBy')
        .withTitle('Created By').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<a href="#">' + data + '</a>';
                
            ),
        DTColumnBuilder.newColumn('customerDetailsMap.agentName')
        .withTitle('Agent Name').renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else 
                    return '<p>' + data + '</p>';
                
            ),
        DTColumnBuilder
        .newColumn(null)
        .withTitle('')
        .notSortable()
        .renderWith(
            function (data, type, full, meta) 
                if (full.length === 0) 
                    return "";
                 else if (isAgentUsr) 
                    return "";
                 else if (full.salesOrders.isArchived != 1) 
                    return '<a href="#" data-toggle="modal" data-target="#soWorkOrders" class="soWorkOrders">' +
                        'work order' +
                        '</a><br>' +
                        '<br>' +
                        '<a class="soInvoice" href="#" data-toggle="modal" data-target="#soInvoice">' +
                        'invoices' + '</a>';
                 else 
                    return "";
                
            )
    ];
    vm.dtInstance = ;

"fromallSoDt"" 和 "toSoDate" 是我的两个日期选择器字段 我需要以下答案吗?

1) 需要为“toSoDate”设置今天的值,而“fromallSoDt”需要设置前六个月的值

2) 在单击提交按钮时,我有另一个函数调用,它也获取数据并绑定到下面的数据表,当我自动单击提交时,此日期选择器值设置为我在上面代码中设置的先前值

var pre = new Date();
                var newd = new Date(pre.setMonth(pre.getMonth() - 3));
                var ddd = newd.getDate();
                var mmm = newd.getMonth() + 1; // January is 0!
                var yyyyy = newd.getFullYear();

                if (ddd < 10) 
                    ddd = '0' + ddd
                

                if (mmm < 10) 
                    mmm = '0' + mmm
                

                var td = mmm + '/' + ddd + '/' + yyyyy;

                var pre = td;

                document.getElementById('fromallSoDt').value = formatDate(
                        new Date(getDateFromFormat(td, "mm/dd/yyyy")),
                        "dd MMM, yy");



                $('#fromallSoDt').datepicker(

                    autoclose: true,
                    format: "dd M, yy"
                );


debugger
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1; // January is 0!
                var yyyy = today.getFullYear();

                if (dd < 10) 
                    dd = '0' + dd
                

                if (mm < 10) 
                    mm = '0' + mm
                

                today = mm + '/' + dd + '/' + yyyy;
                $('#fromallSoDt').datepicker(

                    autoclose: true,
                    format: "dd M, yy"
                );

【问题讨论】:

【参考方案1】:

你需要像这样设置值

var d = new Date();
var currMonth = d.getMonth();
var currYear = d.getFullYear();
var startDate = new Date(currYear, currMonth, 1);

 $('#fromallSoDt').datepicker(
   autoclose: true,
   format: "dd M, yy"
   );

 $('#fromallSoDt').datepicker("setDate", startDate);

【讨论】:

你好@KishoreKumar Mani,我在上面使用它绑定了 18 年 3 月 1 日 .. 为什么会发生任何线索?【参考方案2】:
var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1; // January is 0!
            var yyyy = today.getFullYear();

            if (dd < 10) 
                dd = '0' + dd
            

            if (mm < 10) 
                mm = '0' + mm
            

            today = dd + '/' + mm + '/' + yyyy;

            $('#toSoDate').datepicker(
                autoclose: true,

                format: "dd M, yyyy"

            ); 
    $('#toSoDate').datepicker("setDate", next);

我在@KishoreKumar Mani 的帮助下找到了这个解决方案,谢谢

【讨论】:

以上是关于在动态创建的表单后 ajax 调用中将默认值设置为日期选择器的主要内容,如果未能解决你的问题,请参考以下文章

如何在radiogroup中将选中的单选按钮设置为默认值?

在 Laravel 5 中将多行从动态表单保存到数据库

如何在 SQL Server 中将函数设置为默认值?

如何设置select2 ajax预选值?

使用 Django,如何在模板中动态设置 ModelForm 字段值?

Redux 表单默认值