Click here to Skip to main content
15,896,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Im am using a javascript function to prevent entering letters into a text box on my site... The code looks like this

C#
function checkInp() {

            var x = document.forms["form1"]["txtIfCh1"].value;
                if (isNaN(x)) {
                    alert("Треба да внесувате број!");
                    return false;
                }

        }

and I add onkeypress="checkInp()" tho the text box...

this code works fine, but i have 10 textboxex to check for letters.. How can the functiont be changed in the way that i will have jsut oune function not 10.??
Posted
Updated 5-Jan-22 19:33pm

Try this:
XML
<!DOCTYPE html>
<html>
<head>
<script>
function checkInp() {
 var input = document.getElementsByTagName("input");
 for (var i = 0; i < input.length; i++) {
    if (input[i].type == "text"){
        if (isNaN(input[i].value)){
           alert("Not a number!");
            return false;
        }
    }
 }
}
</script>
</head>
<body>
<form onsubmit="return checkInp();">
<input type="text" id="textbox1" value="">
<input type="text" id="textbox2" value="">
<input type="submit" value="submit">
</form>
</body>
</html>
 
Share this answer
 
v4
Comments
Voley 18-Nov-14 7:00am    
Thankyou, the function was helpful :)
Peter Leow 18-Nov-14 7:46am    
You are welcome.
Voley 27-Nov-14 10:17am    
I have an additional problem with the function:

function checkInp() {
var input = document.getElementsByTagName("input");
for (var i =0; i < input.length; i++) {
if (input[i].type == "text") {
if (isNaN(input[i].value)) {
alert("Not Number");
return false;
}
}
}
}

this fucntion works finde till I have to input negative numbers and decimal numbers wich I separet them with comma (,) ex: -12.3 or -3,4 ... How can I exclude , and - to recognize them as caracters?
Improve solution Permalink Posted 1 sec ago
I have an additional problem with the function:

C#
function checkInp() {
            var input = document.getElementsByTagName("input");
            for (var i =0; i < input.length; i++) {
                if (input[i].type == "text") {
                    if (isNaN(input[i].value)) {
                        alert("Треба да внесувате бројка!");
                        return false;
                    }
                }
            }
        }


this fucntion works finde till I have to input negative numbers and decimal numbers wich I separet them with comma (,) ex: -12.3 or -3,4 ... How can I exclude , and - to recognize them as caracters?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900