0

So I've run into a snag trying to make a date calculator in Javascript. I'm fairly new to Javascript so I feel like I'm diving in a little deep, but here's a rundown of what I'm trying to accomplish.

Here's a jsfiddle: http://jsfiddle.net/b52hamw7/2/

I first have a form in my HTML formatted as follows:

<form>
   <p class="instructions">I need my items by:</p><br>
   <input type="date" name="date" value="" id="date"/>
   <input type="button" value="Submit" id="submit">
</form>
<p>Be sure to order by:</p><p id="dateoutput"></p>

The idea here is that a user will input a date into the form and then a javascript code will add 10 days to it and output the day that they need to order by, formatted as a date.

Here's the script that I have so far, which I know isn't close to working, but it's a start I guess:

<script>
document.getElementsByName("submit").onclick = function() {
  var dateIn = document.getElementsById("date").value;
  var addDays = 10;
  var dateOut = dateIn + addDays; 
};

document.getElementById("dateoutput").innerHTML = dateOut;
</script>

I really appreciate any direction you can give me on this one. Thanks in advance!

Chris Patty
  • 189
  • 1
  • 3
  • 12

1 Answers1

0

There are multiple typos and issues in your code. I will list some of them below to get you on the right track.

1) Your line document.getElementsByName("submit").onclick.... is attempting to search for an element with name="submit" of which you have none in your HTML.

2) The next line var dateIn = document.getElementsById("date").value; has a typo, it should be: document.getElementById("date").value. You have an extra 's'.

3) The line document.getElementsById("dateoutput").innerHTML = dateOut; has 3 problems. First you have the extra 's' as in point 2 above. Second, you are attempting to assign the innerHTML to the value of variable that you have lost scope for. And Finally it is not executed within the context of the click function and is executed immediately when it is parsed as opposed to when the click event occurs. Therefore it needs to be moved within your onclick handler function.

4) With respect to adding days to the date. Please check out Add days to JavaScript Date. Right now you are attempting to to add 10 to a string value that you are pulling from the input element which simply concatenates the string '10' onto the end of your date string. You need to convert it to a date object and then add the 10 days. This is explained in code examples in the link provided

Community
  • 1
  • 1
Brian
  • 199
  • 6