Programmer Programmer -4 years ago 80
HTML Question

Checking if input has a int in it Javascript

I am working on a HTML page and can't seem to figure out how to check if the user input has an integer in it. I have tried parseInt, userInput.charAt(i) in a for loop, isNaN. Nothing seems to be working.

This is my HTML

<label for="author" id="author">Favorite Book Author: </label>
<input type="text" name="author" id="authorText">


This is my JavaScript

function checkAuthor(){
var userInput = $("authorText").value;
for(var i = 0; i < userInput.length; i++)
{
if(userInput.charAt(i) <= 0 || userInput.charAt(i) > 0)
{
addError("There is a number in 'Favorite Book Author' input");
return false;
}
else
return true;
}
}


I need to see if there is any integer that was entered by the user. If the input was "Mark5", "Ma5rk", "5", I need it to catch that 5 and display an error. Is there anyway that will work? I have a feeling that the .charAt is not working because it is recognizing the ints as strings, but I have tried to do a parseInt of every single

var x = parseInt(userInput.charAt(i));


inside the for loop, and then compared x inside the if statements. But nothing seemed to work

The addError function is this

function addError(text){
var mylist = window.document.createElement("li");
var myText = window.document.createTextNode(text);
mylist.appendChild(myText);
window.document.getElementByTagName("ul")[0].appendChild(mylist);
}

Answer Source

You should check whether the char code between 48 and 57

function checkAuthor(){
    var userInput = $("authorText").value;
    for(var i = 0; i < userInput.length; i++)
    {
        var c = userInput.charAt(i).charCodeAt(0);
        if(c <= 57 && c >= 48)
        {
            addError("There is a number in 'Favorite Book Author' input");
            return false;
        }
           
    }
     return true;

}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download