0

I'm having a JS problem and it could be that I'm just stuck, but maybe one of you could help me out.

I have the following index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Calendar</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="stylesheets/base.css">
        <link rel="stylesheet" href="stylesheets/content.css">
        <link rel="stylesheet" href="stylesheets/calendar.css">
        <script
            type="application/javascript"
            src="scripts/try.js">
        </script>
        <script src="scripts/jquery-3.3.1.min.js"></script>
    </head>
    <body 
        onload="init()">
        <div id="content"> 
            <div class="year">
                <ul>
                    <li id="year">year</li>
                    <li class="prev" id="prevmonth" onclick="changeYear()">&#10094;</li>
                    <li class="next" id="nextmonth" onclick="changeYear2()">&#10095;</li>
                </ul>
            </div>
            <hr>
            <div class="month">
                <ul>
                    <li id="month">month</li>
                    <li class="prev" id="prevyear" onclick="changeMonth()">&#10094;</li>
                    <li class="next" id="prevyear" onclick="changeMonth2()">&#10095;</li>
                 </ul>
            </div>
        </div>
        <div id="calendar">
            <table id="tablecalendar">
            </table>
        </div>
    </body>
</html>

which loads init(). This function contains the following code:

function init() {
    var months = ["January", "February", "March", "April", "May", "June", 
    "July", "August", "September", "October", "November", "December"];
    let monthsextension = ["nothing"];
    var months2 = monthsextension.concat(months); 
    today = new Date();
    var month2 = today.getMonth();
    var year = today.getFullYear();
    document.getElementById("month").innerHTML = months[month2];
    document.getElementById("year").innerHTML = year;
    displayC();
}

the function dispayC, has two functions to count up or down from the year:

function changeYear(){
    var year = document.getElementById("year").innerHTML;
    var year = year-1;
    document.getElementById("year").innerHTML = year;
}

function changeYear2(){
    var year2 = document.getElementById("year").innerHTML;
    console.log(year2);
    console.log(year2+1);
    year2 = year2+1;
    console.log(year2);
    document.getElementById("year").innerHTML = year2;
}

now, function "changeYear" works as I would like it, but "changeYear2" doesn't add 1 to the year, but adds the digit one to the year.

Example:
"2019" becomes "20191"
with a second click on the counter arrow it becomes "201911"

How come I can subtract but not add to the year?

Hope it's not too much code, I try to cut it down as much as I could.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
origins
  • 3
  • 1
  • 2
    `var year2 = document.getElementById("year").innerHTML;` returns a string. Convert it to an integer. – j08691 Apr 15 '19 at 19:56
  • Possible duplicate of [JavaScript function to add X months to a date](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date) – jordiburgos Apr 15 '19 at 19:58

4 Answers4

0

The - operator coerces the operands to number (there's no such thing as string subtraction), the + operator does not (because for strings, + means concatenation).

console.log("7" - "2");
console.log("7" + "2");

parseInt that innerHTML, and it'll work.

mbojko
  • 13,503
  • 1
  • 16
  • 26
0

in var year2 = document.getElementById("year").innerHTML;

change it to

var year2 = parseInt(document.getElementById("year").innerHTML);

Year2 is defined as a string by default, which when you add the number to it, simply adds it to the string. You must convert the string to a number through parseInt() (or parseFloat(), etc).

Timble
  • 499
  • 4
  • 15
0

HTML has one data type only: strings. When you do this:

var year2 = document.getElementById("year").innerHTML;

You aren't creating a Date object in JavaScript, you are creating a string. So, when you then do this:

console.log(year2+1);

You aren't adding, you are concatenating;

You'll need to convert the HTML string into a date and then use Date methods to modify it. Here's an example:

let dateString = document.querySelector("input");
let btn = document.querySelector("button");
let output= document.querySelector("div");

btn.addEventListener("click", function(){

  // All we have at this point is a string
  console.log(dateString.value, typeof dateString.value);

  // Create new date based on string
  let actualDate = new Date(dateString.value);

  console.log(actualDate, typeof actualDate);
  
  // Adjust the year portion of the date
  actualDate.setYear(actualDate.getYear() +1);
  
  // Send the string representation back to the document
  output.textContent = actualDate;  
});
Please enter a date (mm/dd/yyyy): <input>
<button>Make Date</button>
<div></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

It's so common for variables to be cast as strings in Javascript when you don't expect them to be. Whenever you subtract two variables Javascript is smart enough to assume they're both numbers. When you add, however, Javascript doesn't know if they're numbers or strings (since the + operator is used for both).

You can always coerce a string into a number by doing Number(year) + 1 or by using parseInt(year) + 1

j3e8
  • 51
  • 2
  • Or, by doing `+year`. – Scott Marcus Apr 15 '19 at 20:06
  • thank you very much. It's weird that I don't need to convert it when I'm subtracting, but just happy it works :) – origins Apr 21 '19 at 12:11
  • It's because Javascript is a loosely typed language and it determines if a variable is a String or Number at run-time. When it sees two variables with a `+` between them it can't know for sure if they should be Strings or Numbers since both of them can use the `+` operator. However, when it sees a `-` it knows they need to be coerced into Numbers because only Numbers can make use of the `-` operator. – j3e8 Apr 22 '19 at 15:48