Reputation: 29316
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>.";
}
}
Upvotes: 0
Views: 386
Reputation: 116
You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.
Upvotes: 0
Reputation: 42496
You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
/* error stuff */
}
Upvotes: 2