Search code examples
javascriptcharacterletter

In JavaScript, how do I detect whether or not the input contains letters?


My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.

HTML

<label for="bannerID">Banner ID: B</label><input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" /><br /> 

<p id="bannerOutput"></p>

JavaScript

function showBannerID() {

var textInput = document.getElementById('bannerID').value;

if (textInput.length == 0) {
    document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Field can't be empty!</strong>";
}
else if (textInput.charAt(0) == "B") {
    document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Please omit the B! It's not necessary.</strong>
}
else {
    document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: <strong>B" + textInput + "</strong>.";
}
}

Solution

  • You can use isNaN() (Not a Number) as a condition.

    isNaN(123) would give false, isNaN("hello") would give true.