jquery,date , Add days, weeks, months to date using jQuery

Add days, weeks, months to date using jQuery


Tag: jquery,date

I have a form which lets the user select an invoice date and payment terms. The payment terms are; 1 week from invoice date, 4 weeks from invoice date, 1 month from invoice date, etc.

When the user has selected an invoice date and the payment terms I then want to generate the invoice due date.

My question is, how do I add to a date in jQuery and how do I do it in a reliable way. For example, taking into account leap years and the varying number of days in each month. For example, adding 1 month to October 31st should be November 30th and not November 31st.

I have found a few solutions by searching Google but they seem to fail on leap years, etc.


jQuery is not for DateTime manipulation. It's for querying and manipulating DOM objects. For what you need, you can either implement that yourself, or use a specialized third-party library.

Moment.js is pretty neat.


moment().subtract(10, 'days').calendar(); // 06/12/2015
moment().subtract(6, 'days').calendar();  // Last Tuesday at 1:51 PM
moment().subtract(3, 'days').calendar();  // Last Friday at 1:51 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 1:51 PM
moment().calendar();                      // Today at 1:51 PM
moment().add(1, 'days').calendar();       // Tomorrow at 1:51 PM
moment().add(3, 'days').calendar();       // Thursday at 1:51 PM
moment().add(10, 'days'

More examples here: http://momentjs.com/


Fancybox thumbnail is not working

I'm trying to imitate this jsfiddle: http://jsfiddle.net/kevin11189/uZCC6/1269/ however the thumbnails are not appearing. Here's my code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Gallery</title> <meta name="description" content="An interactive getting started guide for Brackets."> <link rel="stylesheet" href=""> <style> .hidden { display: none; } </style> <!-- Add jQuery library -->...

Parsing XML array using Jquery

I have stuck up with an issue of passing XML using Jquery. I am getting empty array while traversing to jquery.Please help me how to get datas from XML array. I have mentioned my code below. XML <?xml version="1.0" encoding="UTF-8"?> <json> <json> <CustomerName>999GIZA MID INSURANCEAND SERVICES PVT LTD</CustomerName> <mobiLastReceiptDate>null</mobiLastReceiptDate> </json>...

Setting radio button checked true on button click

I have a table cell that lights up when selected. There will be many buttons on the page but only one choice can be made at a time. How can I make them mutually exclusive using hidden input radio tags? (in order to handle the group later) <td class="choice-option"> <input...

How to send current page number in Ajax request

I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this: var pageNo = 1; $('#propertyTable').dataTable( { "processing": true, "serverSide": true, "ajax": "${contextPath}/admin/getNextPageData/"+pageNo+"/"+10, "columns": [ { "data": "propertyId" }, { "data": "propertyname" }, { "data": "propertyType"...

How to remove legend from bottom of chart - amcharts

Can you please help me out to remove the legend (of y-axis data) from the below the line-chart. This is the icon that helps to remove the corresponding line from the line-chart. See inline image...

JQuery mutiple post in the same time

I have three functions ,and every function post to special php page to get data.. and every function need some time because every php script need some time .. function nb1() { $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error"); }); } function nb2() {...

add value to existing class in jQuery

EDIT - included the page where the problem is visualized - http://www.openmindedmedia.nl/testfase/julius/ First of all, I have searched quite some hours to find this.. I presume it has an easy fix but I'm really new to jQuery and Javascript, so I'm here for your help. The problem I'm working with...

Javascript change the souce of all images present inside a string

I have a message or string which contain both text as well as images as below. var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>'; Before appending this to the the chat div i want to replace the src of the images to a default image. How can...

copy last column of one table to another table based on some condition

I have two tables. I want to take last column of table3 and put in to table4 eg:- table3 Names Process_id total construction 1 1111 construction_1 1 0000 engineering 1 2222 permitting 1 3333 eg:- table4 Names Process_id construction 1005 engineering 1005 permitting 1005 final result of table4 output will...

Onclick add html content and remove it by clicking “delete” link

I have some issue, help me please to find where is the mistake. $(document).ready(function(){ $(function() { var scntDiv = $('#p_scents'); var i = $('#p_scents .row-wrap').size() + 1; $('body').on('click', '.add-item', function() { $('<div class="row-wrap cf"><div class="col-md-3 col-sm-3 col-xs-12"><input type="text" placeholder="Наименование" name="item_name' + i +'"></div><div class="col-md-2 col-sm-2 col-xs-12"><input type="text" placeholder="Количество" name="item_count' +...

change icon on collapse in Bootstrap 2.3 not in bootstrap 3

I am using bootstrap 2.3 collapse in my project. I need to change icons on collapse means on show and hide I need to change icons. with bootstrap 3 some shown and hidden functions are showing in internet but I need with Bootstrap 2.3. Please let me know how to...

bootstrap - dynamically changing jumbotron background image

I'm trying to change the background image of the jumbotron div with jQuery when a new tab is clicked, like this: $(".about").click(function(){ $('.active').toggleClass('active'); $('.about').toggleClass('active'); $('.jumbotron').fadeOut(500); //change background image $('.jumbotron').fadeIn(500); }); I tried using $('.jumbotron').css('background-image',url('/path/to/new/image')); but when I include that line, the jumbotron background image doesn't display at all even before...

How to find the days b/w two long date values

I have two long dates value. For Ex: 1433097000000 1434479400000 Here i have to find the days between these two by jquery For Ex: 15/06/2015 - 22/06/2015 If it is more than 5 days, I want to get from is 15/06/2016, to is 19/06/2015. It is based on long values...

slideToggle state not working with multiple boxes

I'm trying to save the toggle state of collapsable boxes using cookies. Here's my code: HTML: <div class="box_container"> <div class="box_handle"> Title </div> <div class="box" data-title="admin_actions"> Content </div> </div> Javascript: $('div.box_container div.box_handle').click(function() { $(this).next('.box').slideToggle('fast'); }); $.each($('div.box_container div.box_handle'), function(index,value){ if ($.cookie('show_box_' + $(value).next('.box').attr('data-title')) != 'closed'){...

Converting “i+=n” for-loop to $.each

I have the below html structure: <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> Now to group/wrap each 4 items in a separate div I did as below: var div=$('.thumbnail'); for(var i = 0; i < div.length; i+=4) { div.slice(i, i+4).wrapAll("<div...

Datatable event on page change not working

This is what I want when the page is changed: $('#resultTable').on('page.dt', function() { if (document.getElementByID('r_tab').checked()) { $('.r_tab').show(); console.log('page changed on r'); } else { console.log('page changed on p'); $('.p_tab').show(); } }); When I run this code, I am not able to change the page anymore. Clicking on any page number/next...

Bootstrap toggle doesn't display well when added dynamically

I'm trying to add bootstrap toggle switch dynamically but it does not display well after adding it. Thanks for your help! <input id="TheCheckBox" type="checkbox" data-off-text="Yes" data-on-text="No" checked="false" class="BSswitch"> <p> <a class="btn btn-lg btn-primary" href="#">Display another Toggle</a></p> $('.btn').on('click', function () { $('p').after( '<input id="TheCheckBox" type="checkbox" data-off-text="Male" data-on-text="Female" checked="false" class="BSswitch">' ); });...

Get info from dynamic/growing form

Have a form to create a contract, where that contract can have one or more users associated. The area to input the users info, starts with only one field of one user, and one button to add more fields if needed. <div id="utilizadores" class="row"> <div id="utilizador1" class="container-fluid"> <div class="row"> <div...

Adding horizontal space between 2 buttons using javascript

I am dynamically creating submit buttons using javascript. I wanted to know how to introduce horizontal spacing between every other button in the process. My code is var allFields = commonButtons.concat(extraFields); for (var i = 0; i < allFields.length; i++) { var node = document.createElement("input"); var btName = document.getElementById("submit-buttons"); node.setAttribute('data-value',...

Dynamically increasing radio button validation

I have some radio buttons that dynamically increase based on data. What I want is to check if all radio button are selected or not. If they're not, I want to show an error message on that particular row as I am using form substitution to send data to ajax....

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column...

Why is JQuery index() returning 1 for the first element?

In the following line of code, a call to the index() function for the first element in a set returns 1. Why does it not return 0? var firstBlockIndex = $( '.block' ).first().index(); ...

Response 200 OK but Jquery shows error?

I am stuck in kind of a weird problem where I am trying to make a JSONP request to the Open Weather history API to get the weather information for the previous years on the a particular date. fetchHistoryUrl = ''; $.ajax({ method: 'get', url: fetchHistoryUrl, success: function(response){ console.log(response); },...

How to remove all the borders of a selectbox?

How can I remove the all the borders of the selectbox using css or Jquery ? My code, <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option> </select> CSS #doctor_ch{ background-color: #88AFF2; color:#fff; margin-top: 15px; } When I use this code it only changes the arrow style. I want to remove the...

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

JQuery .width() for this element

How can I get width of element which I css. My code: $('a').css({'left':-$(this).width()/2}) ...

Jquery parsley validate not working

if($("#dataform").parsley().isValid()){ $.ajax({ url : '<?php echo base_url();?>index.php/company/final_review?id=<?php echo $this->input->get('id'); ?>', type : 'POST', data : $("#dataform").serialize(), dataType:"json", beforeSend: function(){ $('#remarks').parsley( 'addConstraint', { minlength: 5 }); }, success : function(data){ console.log(data); } }); } This is my ajax part. The plugin is not validating the field it's submitting the form. The...

Redraw text over clearRect HTML5 Canvas

I'm trying to draw text (HTML5 canvas) depending on what option is selected in a select element. It works correctly until there's 2 set of text that appears at the same place. It seems like the clearRect function is the issue. The text won't be redrawn over that cleared space....

Set default value for struts 2 autocompleter

I have implemented a struts 2 autocompleter in which i have used a list of String like this - <sj:autocompleter id="cityId" cssClass="txtfield8" name="outlet.cityName" list="cityList" autoComplete="true" forceValidOption="false" /> How can I set a default value for this, so that every time it loads, a default value will be shown ?...

Get elements containing text from array

I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

jqgrid paging on server side

I'm trying to add server side paging to my grid. In adittion, I have a filter by 'license', 'number' and 'group'. When I press the next page button the controller is called and I obtain the data but my grid is reload on page 1 and I cant view the...

Javscript Replace Text in tags without changing children element HTML and Content

I have a script where I'd like to replace the text anywhere in the body visible to the user like so: $("body").html($("body").html().replace(/replaced word/g,'HELLO')); This works but it works to well. Whenever "replaced word" is within a tag, like a href, or span, or div, or anything it throws off all...

How do I retain search engine accessibility when loading external file into html

I plan to: $('#main.sidecontent').load('/sidecontent.html'); and insert: <div class="sidecontent" id="main"></div> a div on several html pages since the content of this div is the same and I try to straighten my workflow, basically avoiding editing every single html page when this content div changes. My questions: Is this method recommended for...

How to remove unmatched row in html table using jquery

I have two tables. I want to delete unmatching rows. Compare with first column in Table1 and compare with first column in Table2. Table1 111 aaa 222 bbb 333 ccc Table2 333 xxx 444 zzz 111 vvv result of Table2 333 xxx 111 vvv I tried some thing here Please...

change css dynamically by selecting dropdown list item

I have the following Dropdownlist with yes or no options-:` <asp:DropDownList ID="ddlchangecss" runat="server"> <asp:ListItem Text="yes">yes</asp:ListItem> <asp:ListItem Text="no"></asp:ListItem> </asp:DropDownList> i want to add a css dynamically like that-: .imgFullWidth { width: 100%; height: auto; float: left; margin: 0px 0px 20px 0px; } when I select yes option in Dropdownlist. How can...

jQuery click open one dropdown

In a site I have several 'dropdown' which become visible when you press a plus sign. I did this with jQuery (see code below), but when pressing the button every dorpdown opens. How can I only open the dropdown where the button is pressed (Without writing this code for every...

show/hide an overflow div on anchor

I'm trying to make a div appear (if not already visible) and be scrolled to a specific anchor. I found this answer and try to use it but it looks like it doesn't work well... http://stackoverflow.com/a/7513110/3703099 My code : http://jsfiddle.net/0sq2rfcx/9/ As you can see, when you click on button it...

Identifier starts immediately after numeric literal

I'm trying to get the current logged in usersID in my jquery function var userID = @User.Identity.GetUserId(); Many answers on this page say that I have to do something like \"@User.Identity.GetUserId()\" But it dont seem to work, can someone tell me how to fix it. Its for my ajax post....

Target next instance of an element/div

I have the following HTML structure and JavaScript file: .html <li> <button class="show-more"></button> some more elements <div class="hidden"></div> </li> JavaScript $( ".show-more" ).click(function() { event.preventDefault(); $( this ).next().slideToggle( "fast", function() { }); }); I need the click event to toggle the next first instance of .hidden, however the click event...

Binding Checkbox to td element

I'm currently developing a web application that populates a table (using the dynatable jquery plugin) using json. One of my needs is to bind a checkbox to a particular column (email) and to be able to retrieve a list of selected addresses and convert them into a comma separated string....

writing jQuery instead of $ to access controls in a page

Can I write jQuery( "body" ).append('Hello') instead of $( "body" ).append('Hello') in jQuery

Confused by JQuery Docs about .submit() event

I saw a example describe in Official Document https://api.jquery.com/submit/ $( "#target" ).submit(function( event ) { alert( "Handler for .submit() called." ); event.preventDefault(); }); Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault()...

Detect when the jQuery UI slider is being moved?

I have this custom video time UI slider to change the time of the YouTube video when scrubbed. My problem is that when the video is trying to load when the user is moving the slider, it causes the handle to jerk around and flip around. What I'm trying to...

Background-image style with JS not working in ie9

I'm working on a site and im having some issues with my slider in IE9. What I've done is that I've made a div that gets the background image changed every few seconds depending on the img tags within. You can see it in function here: http://diakondk.quine.pil.dk/ It works wonders...

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

jQuery validate equalTo

I would like to use jQuery validate() plugin using the equalTo to validate a signature field, basically the signature field must match the first name and last name field, is this possible using the validate() plugin? http://jqueryvalidation.org/equalTo-method/ shows me how to check if it is equal to another input, but...

Rerendering Handlebars template upon data change

I have a template that shows a button based on some boolean in a JSON-object. There are two different buttons it can show. The code for compiling the template: source = $('#some-template').html(); // Get the HTML source of the template template = Handlebars.compile(source); // Compile it $('#some-div-container').html(template(someJsonObject)); Let's say the...

want to show and hide text using “this” jquery

I want to achieve this effect with this because I have several paragraphs like this so I don't wanna use id for each paragraph <p class="desc_services_subheading"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,...

Click on link next link should be display on same page

I have a single page website and need to link the navigation to IDs in the page. I have three links: "About us", "Our Project", "contact". So if user clicks on "About ", the About section will be displayed, same with other links. Inside Our project there is Two buttons...