0

I try to get variable from a form to add dates to current date. I get the number, but the outcome date is way off. If I hardcore the number it works fine and when I try to display the variable it gets right.

Why does it not display the right date?

 $("input[name='newDate']").on('ifClicked',function addDays(date,days) { 
     var today = new Date();
     var numberOfDaysToAdd = this.value; 
     today.setDate(today.getDate() + (numberOfDaysToAdd));
     alert(today +'value: ' + numberOfDaysToAdd);  
});
1
  • What is the use of function name addDays and arguments date,days? Are you using it anywhere inside the click handler? Commented Mar 14, 2016 at 10:47

1 Answer 1

2

I try to get variable from a form to add dates to current date. I get the number, but the outcome date is way off

Use parseInt();. I think you are trying to add a string value to the date and it is messing up. Parsing it to integer might help.

parseInt("12",10) if your input value is 12.

So use the below code.

var today = new Date();
var numberOfDaysToAdd = parseInt(this.value,10); //parse to Integer
today.setDate(today.getDate() + (numberOfDaysToAdd));
alert(today + 'value: ' + numberOfDaysToAdd);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. You are a life saver :-)
Glad to know it worked for you. You can mark my response as answer Only if it helped you to resolve the issue.
Always use the second parameter to parseInt(value, radix). If you don't and your value starts with a leading zero, it will be interpreted as octal.
@user3114969 you need to use the updated answer. the change is in the parseInt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.