Ahmed Abbas Ahmed Abbas - 4 months ago 22
HTML Question

Validate if i enter Alphabet

I make a simple program that when i enter any number in text box it add 3 in it.
I want to validate if user enter text then it shows a message "YOU ENTER TEXT".
if i enter any text my if-else is not working
here is my code
HTML:

<input type="text" id="txt1">
<input type="button" value="EXECUTE" onClick="add()">
<p id="demo1"></p>


JS:

function add(){
var num1=document.getElementById("txt1").value;
var a=parseInt(num1);

if(typeof a==='String'){
document.getElementById("demo1").innerHTML="THIS IS STRING";
}
else{

var ans=(a+3);
document.getElementById("demo1").innerHTML=ans;
}
}

Answer

To achieve expected result use isNaN() instead of typeof

function add() {
  var num1 = document.getElementById("txt1").value;
  var a = parseInt(num1);

  if (isNaN(a)) {
    document.getElementById("demo1").innerHTML = "THIS IS STRING";
  } else {

    var ans = (a + 3);
    document.getElementById("demo1").innerHTML = ans;
  }
}

http://codepen.io/nagasai/pen/NAyAWL