jQuery

Adding days to given date in jQuery

Here Laxmi Kant has explained with an example, Adding days to given date in jQuery.
This article will illustrate How to Adding days to given date in jQuery when enter value in Enter Days field.

In this article you will learn with an example, How to Adding days to given date in jQuery.
If you want to add days to selected date which will reflect in another textbox as new date. though the code is working.

HTML Markup
The HTML Markup consists of an HTML TextBox type date and number.

<body>
    <label for="date">Enter Date:</label>
    <input type="date" id="startdate" name="date1">
    <label for="enterDays">Enter Days:</label>
    <input type="number" id="adddays" placeholder="Days" />
    <label for="Adddate">After Add Date:</label>
    <input type="text" id="adddate" name="adddate">

</body>

jQuery Code
Inside the jQuery document ready event handler, The change event occurs when the value of an element has been changed then this value will be added at date.

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
        $(document).ready(function () {
            $("#adddays").change(function () {
                var addDays = $("#adddays").val() ? $("#adddays").val() : 0;
                var startDateVal = $("#startdate").val();
                var ModifyInDate = new Date(setDateFormat(startDateVal));
                var NewDate = ModifyInDate.setDate(ModifyInDate.getDate() + parseInt(addDays));
                NewDate = new Date(NewDate);
                if (NewDate != "Invalid Date")
                    $("#adddate").val(setDateFormat(NewDate));


            });


        });
        //This function is used for set date formate
        function setDateFormat(date) {
            DateObj = new Date(date);
            var day = DateObj.getDate();
            var month = DateObj.getMonth() + 1;
            var fullYear = DateObj.getFullYear().toString();
            var setformattedDate = '';
            setformattedDate = getDigitToFormat(month) + '/' + getDigitToFormat(day)   + '/' + fullYear;
            return setformattedDate;
        }
        function getDigitToFormat(val) {

            if (val < 10) {
                val = '0' + val;
            }

            return val.toString();
        }

    </script>

Output :
adding-days-to-given-date-in-jquery

Leave a Reply

Your email address will not be published. Required fields are marked *