How can I check if the input is empty in JavaScript? [duplicate]

I am trying to make a factorial calculator. How can I check if the input is empty or not? I tried 'null'. But it didn't work or I couldn't use it properly.
sorry for the stupid question. I am newbie in JavaScript

function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function () {
    if( !(isNaN(input))) {
      var result = 1;
      for(var i = 1; i <= input; i++ ) {
        result = result * i
      }
      return result;
    }
    else if (input == null){
      return "Please input a number"
    }
    else{
      return "Please input a number"
    }
  }

  document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p> 
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>

Answers:

Answer

function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function() {
    if (input.trim() == '') {
      return "Please input a number"
    } else if (!(isNaN(input))) {
      var result = 1;
      for (var i = 1; i <= input; i++) {
        result = result * i
      }
      return result;
    }

  }

  document.getElementById("input2").value = ever();
}
<p>Input:
  <input type="text" id="input1" />
</p>
<p>Input:
  <input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span> 
</p>

Answer

is that what you looking for?

function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function () {
    if(input.match(/\D/) == null){ // changes made here
      var result = 1;
      for(var i = 1; i <= input; i++ ) {
        result = result * i
      }
      return result;
    }
    else{ // one else is enough
      return "Please input a number"
    }
  }

  document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p> 
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>

Answer

When you use .value you get a string value in return. This means that when you enter nothing in the input it'll return ""

So you should change this piece of code input == null

Into this input === ""

Note that I also wrote === instead of == Using === in javascript is faster than == when the objects are of the same type.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.