动态添加JQuery日期时间选择器 [英] Dynamically adding JQuery date time picker

查看:91
本文介绍了动态添加JQuery日期时间选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我已经编写了一个javascript函数来将一些文本框添加到div中。我希望文本框的行为与Jquery datepicker相同。



我在页面中添加了Jquery引用,并且我已经写了$(。className).datepicker() JS功能的结束。但是它没有用。我也试过$(。className).datepicker(刷新),但是徒劳无功。



这是我的html文件

Hi,

I have written a javascript function to add some textboxes dymanically to a div. I want the textbox to behave as Jquery datepicker.

I have added Jquery references in my page and i have written $(".className).datepicker() at the end of the JS function. But its not working. I also tried $(".className).datepicker("refresh") , but in vain .

This is my html file

<!DOCTYPE html>


<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</head>
<body>
    <div id="1"></div>
    <input type="button" id="btn" onclick="Create();">
</body>
</html>

<script type="text/javascript">

    function Create() {

        for (var i = 0; i < 10; i++) {
            var datePicker = "<input type='text' id='datePicker" + i + "' class='date'/>";
            $("#1").append(datePicker);
        }
        $(".date").datepicker("refresh");

    }
</script>





更新时间我的ascx页面





Updated with my ascx page

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MemoDashBoard.ascx.cs" Inherits="KPMG.DE.eGroup.UI.WebParts.MemoDashBoard.MemoDashBoard" %>
<link type="text/css" href="../../_layouts/15/KPMG.DE.eGroup.UI/css/Style-GAnG.css" rel="stylesheet" />

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>

<script type="text/javascript">

    var inEditMode = false;
    var currentMemoDates = [];
    var newMemoDates = [];
    var localeID = "";
    var AuditType = "";

    $(window).unload(function () {
        if (inEditMode) {

            if (confirm("You are about to leave the current page. All your changes will be lost. Do you want to continue?")) {

            }
            else {

            }
        }
    });

    function warning() {
        if (inEditMode == true && true) {
            return "You are about to leave the current page. All your changes will be lost. Do you want to continue?";
        }
    }

    $(window).onbeforeunload = warning;

    $(document).ready(function () {

        localeID = $("#" + '<%= hdnLocale.ClientID %>').val();
    });

        function MemoDashboardEdit() {

            //Setting the edit flag to true
            inEditMode = true;

            BindDatePickers();

            //Checking whether the site is in Prepared For Audit stage
            //var isPreparedForAudit = GetSiteStatus(_spPageContextInfo.siteAbsoluteUrl, "Group Audit Information", "", "", "");
            //if (isPreparedForAudit) {

            //    BindDatePickers();
            //}
            //else {
            //    $("#errorMessage").text("Prepared For Audit not done.");
            //}
        }

        //Getting start audit status
        function GetSiteStatus(url, listname, query, complete, failure) {

            var isPreparedForAudit = true;
            // Executing our items via an ajax request
            $.ajax({
                url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
                method: "GET",
                async: false,
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
                    if (data.d.results.length == 0) {
                        isPreparedForAudit = false;
                    }
                    else {
                        if (data.d.results[0].AuditType == "YE") {
                            AuditType = "Year End Memos";
                        }
                        else if (data.d.results[0].AuditType == "Q1") {
                            AuditType = "Q1";
                        }
                        else if (data.d.results[0].AuditType == "Q2") {
                            AuditType = "Q2";
                        }
                        else if (data.d.results[0].AuditType == "Q3") {
                            AuditType = "Q3";
                        }
                    }
                },
                error: FetchFailed
            });
            return isPreparedForAudit;
        }

        //Creating the calendar for all the memo field
        function BindDatePickers() {

            //Changing the button on click to validate the data
            $("#EditDashBoard").off('click', 'a').on('click', ValidateData);
            $("#EditDashBoard").attr('value', 'Save');

            //Adding new date pickers for each memo date fields
            var index = 0;
            $(".gridStyle td a").each(function () {

                if ($(this).attr('href').toLowerCase().indexOf("workflowview.aspx") < 0) {

                    //Memo Name 
                    var memoURL = $(this).attr('href').split('?')[0];
                    var memoName = memoURL.split('/')[memoURL.split('/').length - 1];

                    //Providing id for the anchor tag
                    $(this).attr("id", "hyp_" + memoName + "_memo" + index);

                    //hiding the currend date anchor date
                    $(this).hide();

                    //Make the datetime pickers visible
                    //$("#auditDate_" + memoName + "_memo" + index).show();

                    var datePicker = "<input type='text' id='auditDate_" + memoName + "_memo" + index + "' class='hasDatepicker'/>";
                    $(this).parent().append(datePicker);
                    index++;
                }
            });

            $(".hasDatepicker").datepicker();
        }

        function ValidateData() {

            var emptyDates = [];
            var memoDates = [];
            var errorDates = [];



            var tmpDate = new Date();
            var month = tmpDate.getMonth() + 1;
            var day = tmpDate.getDate();
            var currentDate = "";
            //dd/mm/yyyy
            if (localeID == "1031") {
                currentDate = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + tmpDate.getFullYear();
            }
                //mm/dd/yyyy
            else if (localeID == "1033") {
                currentDate = (('' + month).length < 2 ? '0' : '') + month + '/' + (('' + day).length < 2 ? '0' : '') + day + '/' + tmpDate.getFullYear();
            }

            var index = 0;
            var errorPopUpHeader = "";
            var errorPopUpBody = "";

            var index = 0;
            $('.gridStyle td').find('input').each(function () {

                var memoName = $(this).parent().find('a').attr('href').split('?')[0].split('/')[asd.split('/').length - 1];

                //Get the memo audit assembly date here (audit date +60)
                var currentAuditDate = $(this).parent().find('a').text();

                //New audit date from calendar
                var newAuditDate = $(this).val();

                //Audit Assembly Date (Audit date + 60 days)
                var assemblyAuditDate = new Date(currentAuditDate);
                var days = parseInt(60);
                assemblyAuditDate.setDate(date.getDate() + days);

                //If the new date is not null and is not the same as old then do the checking and store it in array for saving
                if (newAuditDate && new Date(newAuditDate) != new Date(currentAuditDate)) {

                    if (new Date(assemblyAuditDate) < new Date(newAuditDate) && newAuditDate > currentDate) {

                        //Setting anchor tag values to 
                        $("#auditDate_" + memoName + "_memo" + index).value(newAuditDate);

                        //Pushing to array for saving
                        var memoDetail = {};//make a new product for each iteration
                        memoDetail['MemoName'] = memoName;
                        memoDetail['ComponentName'] = "Put component name here";
                        memoDetail['Component ID'] = "Put component id here";
                        memoDetail['DueDate'] = newAuditDate;
                        newMemoDates.push(memoDetail);
                    }
                    else {

                        if (newAuditDate < currentDate) {
                            errorPopUpBody += "<tr>";
                            errorPopUpBody += "<td></td><td>" + memoName + "</td>";
                            errorPopUpBody += "<td>" + newAuditDate + "</td><td>Selected date is less than current date.</td>";
                            errorPopUpBody += "</tr>";
                        }
                        else if (assemblyAuditDate > newAuditDate) {
                            errorPopUpBody += "<tr>";
                            errorPopUpBody += "<td></td><td>" + memoName + "</td>";
                            errorPopUpBody += "<td>" + newAuditDate + "</td><td>Selected date is less than audit assembly date</td>";
                            errorPopUpBody += "</tr>";
                        }
                    }
                }

                index++;
                //alert($(this).parent().attr('id'));
            });

            // Create the error table and show as pop up
            if (errorPopUpBody) {
                errorPopUpHeader = "<div class='popUpBtnContainer'>";
                errorPopUpHeader += "<img id='closePopUp' class='floatRight popUpCloseBtn' />";
                errorPopUpHeader += "</div>";
                errorPopUpHeader += "<br class='hSpace10' /><br class='hSpace10' />";
                errorPopUpHeader += "<div class='popupFormHeading'>Invalid Due Dates</div>";
                errorPopUpHeader += "<br class='hSpace10' />";
                errorPopUpHeader += "<table class='formTable'>";
                errorPopUpHeader += "<th>Component ID</th><th>Memo Name</th>";
                errorPopUpHeader += "<th>Proposed Date</th><th>Reason for Warning</th>";
                $("#divError").append(errorPopUpHeader + errorPopUpBody);
                $("#divError").append("</table>");
                $("#divError").append("<label id='validationMessage'>Do you want to Cancel or Save?</label>");
                $("#divError").append("<input type='button' id='saveData' name='saveData' value='Save' />");
                $("#divError").append("<input type='button' id='cancelData' name='cancelData' value='Cancel' />");

                //Calling the pop up window
                ShowValidationWindow();
            }
            else {
                errorPopUpHeader = "<div class='popUpBtnContainer'>";
                errorPopUpHeader += "<img id='closePopUp' class='floatRight popUpCloseBtn' />";
                errorPopUpHeader += "</div>";
                errorPopUpHeader += "<br class='hSpace10' /><br class='hSpace10' />";
                errorPopUpHeader += "<div class='popupFormHeading'>Invalid Due Dates</div>";
                errorPopUpHeader += "<br class='hSpace10' />";
                errorPopUpHeader += "<table class='formTable'>";
                errorPopUpHeader += "<th>Component ID</th><th>Memo Name</th>";
                errorPopUpHeader += "<th>Proposed Date</th><th>Reason for Warning</th>";
                $("#divError").append(errorPopUpHeader);
                $("#divError").append("<tr><td colspan='4'>All dates are valid.</td></tr>");
                $("#divError").append("<input type='button' id='saveData' name='saveData' value='Save' />");
                $("#divError").append("<input type='button' id='cancelData' name='cancelData' value='Cancel' />");
            }
        }

        function ShowValidationWindow() {

            $('#validationPopUp').dialog({
                modal: true,
                dialogClass: 'no-close success-dialog',
                closeOnEscape: false,
                resizable: false,
                width: "auto",
                height: "auto",
                open: function () {
                    $(this).parent().appendTo($("form:first"));
                }
            });

        }

        function ClosePopupWindow() {
            SP.UI.ModalDialog.commonModalDialogClose(1, '1');
        }

        function SaveData() {

            // Call the REST service to save data
            if (selectedmemos != "") {

                var listName = "MemoDashBoard";

                if (newMemoDates) {
                    $.each(newMemoDates, function (key, value) {

                        //Generating Job name
                        var nextno = parseInt(GetPDFJobs(_spPageContextInfo.siteAbsoluteUrl, listName, "?$filter=substringof('GROUP',Title)&$orderby=Created desc&$top=1", "", "")) + 1;
                        var title = "job_" + nextno + "_GROUP_MemoDashBoard";
                        var itemType = getListItemType(listName);
                        var item = {
                            "__metadata": { "type": itemType },
                            "Title": title,
                            "SelectedMemos": memodashboardrequired + "|" + issuedashboardrequired + "|" + selectedmemos
                        };

                        $.ajax({
                            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                            type: "POST",
                            contentType: "application/json;odata=verbose",
                            data: JSON.stringify(item),
                            headers: {
                                "Accept": "application/json;odata=verbose",
                                "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            },
                            success: function (data) {
                                ItemAddSuccess(data);
                            },
                            error: function (data) {
                                ItemAddFailed(data);
                            }
                        });
                    });
                }

            }
            //After save , show the anchor tag visible again and hide the date pickers
            var index = 0;
            $(".gridStyle td a").each(function () {

                var memoName = $(this).attr('href').split('?')[0].split('/')[asd.split('/').length - 1];

                //showing the  anchor date
                $(this).show();

                //Make the datetime pickers hidden
                $("#auditDate_" + memoName + "_memo" + index).hide();

                index++;

            });
        }

        function GenerateValidationPopUp(header, body) {
        }
</script>

<asp:HiddenField ID="hdnLocale" runat="server" />

<div id="validationPopUp" class="popupContainer noPaddingTop memoDashBoardPopupContainer">
</div>

<div class="memoDashboard">
    <div class="mainHeader marginTop10 noMarginBottom">Memo Dashboard</div>



    <div id="divPaging"></div>
    <br class="clear" />
    <div id="divGrid">
        <div class="tabContainer">
            <asp:Button Text="Year End Memos" BorderStyle="None" ID="Memos" CssClass="Initial floatLeft noMarginLeft" runat="server"

                OnClick="Memos_Click" />
            <asp:Button Text="Q1" BorderStyle="None" ID="Q1" CssClass="Initial floatLeft noMarginLeft" runat="server" Visible="false"

                OnClick="Q1_Click" />
            <asp:Button Text="Q2" BorderStyle="None" ID="Q2" CssClass="Initial floatLeft noMarginLeft" runat="server" Visible="false"

                OnClick="Q2_Click" />
            <asp:Button Text="Q3" BorderStyle="None" ID="Q3" CssClass="Initial floatLeft noMarginLeft" runat="server" Visible="false"

                OnClick="Q3_Click" />
        </div>
        <br class="hSpace10" />
        <div id="divLegend" class="tab_ststus_text"  runat="server">
            <img src="../_layouts/15/images/KPMG.DE.eGroup.UI/DashboardImages/legend_eng.PNG" alt="Dashboard Legend"

                id="imgLegend" class="floatLeft" />
        </div>
        <div id="divLegendClient" class="tab_ststus_text"  runat="server" style="display: none">
            <img src="../_layouts/15/images/KPMG.DE.eGroup.UI/DashboardImages/legend_eng_Client.PNG" alt="Dashboard Legend"

                id="img1" class="floatLeft" />
        </div>
        <br class="hSpace10" />
        <div id="filter">
            <div class="container">
                <table cellpadding="0" cellspacing="0" class="formTable">
                    <tr>
                        <td width="50">
                            <label class="label noMarginBottom">Scope</label></td>
                        <td>
                            <asp:DropDownList ID="ddlScope" runat="server" CssClass="combobox noMarginBottom marginRight10 floatLeft"></asp:DropDownList>
                            <asp:Button ID="btnApplyfilter" runat="server" Text="Apply Filter" OnClick="BtnApplyfilter_Click" CssClass="submitBtn floatLeft marginRight10 marginLeft10" />
                            <asp:Button ID="btnClearfilter" runat="server" Text="Clear Filter" OnClick="BtnClearfilter_Click" CssClass="submitBtn floatLeft marginRight10" />
                            <asp:Button ID="btnExport" runat="server" Text="Export" OnClick="BtnExport_Click" CssClass="submitBtn floatLeft marginRight10" />
                            <input type="button" id="EditDashBoard" value="Edit Due Date" />
                        </td>

                    </tr>
                </table>
            </div>

            <br class="hSpace10" />
            <div id="divGRDContainer" class="btnContainer noPaddingLeft noPaddingTop"  runat="server">
                <asp:Button ID="btnPrevious" Text="<"  runat="server" />
                <asp:Button ID="btnNext" Text=">" runat="server" OnClick="BtnNext_Click" CssClass="paginationBtn floatLeft" />
                <asp:HiddenField ID="hdnPage" Visible="false" runat="server"></asp:HiddenField>

            </div>
        </div>

        <div class="container noPaddingTop noPaddingLeft noPaddingRight">
            <table cellpadding="0" cellspacing="0" class="gridStyle">

                <thead>
                    <asp:Repeater runat="server" ID="rptHeaderRow">
                        <ItemTemplate>
                            <th><%# Eval("Caption") %></th>
                        </ItemTemplate>
                    </asp:Repeater>
                </thead>
                <tbody>
                    <asp:ListView ID="listExcelData" runat="server" ItemPlaceholderID="PlaceHolder2">

                        <ItemTemplate>
                            <tr>


                                <asp:ListView runat="server" ID="PlaceHolder2" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.ItemArray %>'>
                                    <ItemTemplate>
                                        <td><%# Container.DataItem %></td>
                                    </ItemTemplate>
                                </asp:ListView>
                            </tr>
                        </ItemTemplate>
                    </asp:ListView>
                </tbody>
            </table>
        </div>
        <div class="notifications">
            <asp:Label ID="lblMsg" runat="server"></asp:Label>

        </div>

    </div>
</div>







Can anyone please help me



Thanks




Can anyone please help me

Thanks

推荐答案

(\".className).datepicker() at the end of the JS function.但它不起作用。 I also tried
(".className).datepicker() at the end of the JS function. But its not working. I also tried


(\".className).datepicker(\"refresh\") , but in vain .



This is my html file

(".className).datepicker("refresh") , but in vain .

This is my html file
<!DOCTYPE html>


<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</head>
<body>
    <div id="1"></div>
    <input type="button" id="btn" onclick="Create();">
</body>
</html>

<script type="text/javascript">

    function Create() {

        for (var i = 0; i < 10; i++) {
            var datePicker = "<input type='text' id='datePicker" + i + "' class='date'/>";


(\"#1\").append(datePicker);
}
("#1").append(datePicker); }


这篇关于动态添加JQuery日期时间选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆