Search code examples
javascriptnumberstypeof

select if typerof vlaue of var is number javascript


I want to get the value of the input with id ticketNum and alert that when clicked. I got that working. I also want to compare the number to 10 if the value is a number using < and >.

The first alert is working fine but the second is not:

 function initElement() {
     var p = document.getElementById("sub");
     p.onclick = showAlert;
 };

 function showAlert() {
     var o = document.getElementById("ticketNum").value;
     alert('la valeur de cet input est ' + o);

     if (typeof o === "number") {
         if (o < 10) {
             alert('inferieur a 10');
         } else {
             alert('superieur a 10');
         }
     }
 };         

Solution

  • For checking whether given text input is number or not you can use isNaN function and then convert it to number using Number function.

    Here's sample code snippet based on question -

    function initElement() {
      var p = document.getElementById("sub");
      p.onclick = showAlert;
    };
    
    function showAlert() {
      var o = document.getElementById("ticketNum").value;
      alert('the input value is ' + o);
    
      if (!isNaN(o)) {
        if (Number(o) < 10) {
          alert('inferior to 10');
        } else {
          alert('superior to 10');
        }
      }
    };
    
    initElement();
    <input id="ticketNum" type="text" />
    <button id="sub">Show Alert</button>