Isaque Brandao
Isaque Brandao

Reputation: 13

How to print something in JavaScript from an if/else statement?

I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.

  var bttn = document.getElementById("agebttn");
  bttn.addEventListener("click", bttnClicked);

  function calculate(startingYear) {
    var dateObj = new Date()
    var currentYear = dateObj.getFullYear()
    return currentYear - startingYear;
  }

  function bttnClicked() {
    console.log("bttn clicked");
    var age = parseInt(document.getElementById('age').value);
    var yearsAlive = calculate(age);

    var html = "You entered " + age;
    html += "<br />You have been alive for " + yearsAlive + " years";
    document.getElementById('answer').innerHTML = html;
  }
<body>
  <h1>Age Calculator</h1>

  <input type="number" id="age" placeholder="Enter your birthyear">
  <input type="button" id="agebttn" value="Calc" />
  <div id="answer">

  </div>
</body>

Upvotes: 0

Views: 4304

Answers (2)

rudy tjhia
rudy tjhia

Reputation: 20

CMIIW

from what i see , you want to print that result from your script logic into your div tag with ID = answer right? and you want to get only number input?

you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition

Upvotes: 0

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

You can check if you were able to parse int or not using isNaN function here:

function bttnClicked() {
    console.log("bttn clicked");
    var age = parseInt(document.getElementById('age').value);

    if(isNaN(age)){
        document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
        return;
    }

    var yearsAlive = calculate(age);

    var html = "You entered " + age;
    html += "<br />You have been alive for " + yearsAlive + " years";
    document.getElementById('answer').innerHTML = html;
  }

Upvotes: 1

Related Questions