Reputation: 41
I have a code to add 5 days to the current date in JavaScript, however I am having trouble to put this in a form. This is my code for the function in the script tags:
function checkDate() {
document.getElementById('dateBtn').onclick = function checkDate () {
var dt = new Date();
dt.setDate(dt.getDate() + 5);
alert(dt);
};
}
I tried calling this function inside a form, with the name and properties:
<form name="Shopping" action="Confirmation_Shop.html" method="get">
To call the function for checking +5 days from the current date, I used the following code to to so:
<input type="button" value="Check Date" onclick="CheckDate()">
When I run the webpage, the button is displayed but does nothing at all, however other buttons such as my 'submit' button and a button linked with a function to check the costs of items on the page using arrays works. I have also tried using this code for the check date button:
<input type="button" value="Check Date" onload="CheckDate()">
I still get the same error when using this, the button does nothing when clicked.
Help would me much appreciated. Thanks!
EDIT: If I run this function on a separate html document, and just make a button within the the body and not a form, it works perfectly fine when I click on it.
Upvotes: 0
Views: 804
Reputation: 48425
The button does do something. It creates an onclick
event for an element (id = 'dateBtn') that doesn't exist (not in your sample code anyway).
I think perhaps what you want is this:
function CheckDate() {
var dt = new Date();
dt.setDate(dt.getDate() + 5);
alert(dt);
}
NOTE: I also changed the casing of your function name so that it matches your html.
personally, I hate doing in-line html event handlers (or whatever you call them). I would much prefer this:
document.onload = function(){
document.getElementById('dateBtn').onclick = CheckDate;
}
function CheckDate() {
var dt = new Date();
dt.setDate(dt.getDate() + 5);
alert(dt);
}
with this html:
<input id="dateBtn" type="button" value="Check Date">
...I'm thinking your problem overall is you have got mixed up trying to do two different ways at the same time
Upvotes: 1