4

I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.

and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?

function addFunc() {
  var x = document.getElementById("num1").value;
  var y = document.getElementById("num2").value;

  if (typeof x == 'string' || typeof y == 'string') {
    var result = parseInt(x) + parseInt(y);
    console.log(result);
  } else {
    alert("Wrong Entry!");
  }
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
Cœur
  • 37,241
  • 25
  • 195
  • 267
NoWeDoR
  • 117
  • 8
  • because "DDDD" is a string. Check to see if it is not a number. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN – epascarello Aug 17 '16 at 14:54
  • 1
    document.getElementById("num1").value will always return string. It doesnt matter what you type in input box - its always a text. To avoid NaN you must do a NaN check with `isNaN()` function. – Alex K Aug 17 '16 at 14:55

1 Answers1

5

The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:

function addFunc() {
    var x = parseInt(document.getElementById("num1").value);
    var y = parseInt(document.getElementById("num2").value);

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>

Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:

function addFunc() {
    var x = +document.getElementById("num1").value;
    var y = +document.getElementById("num2").value;

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>
Community
  • 1
  • 1
Blue
  • 22,608
  • 7
  • 62
  • 92
  • can you enter 1e for first input and 11 for second input and observe the result? – NoWeDoR Aug 17 '16 at 14:58
  • `parseInt()` will attempt to remove all non integer characters before parsing. Is this not what you want? – Blue Aug 17 '16 at 14:59