+ 3
Help making my JavaScript code better! (Answered)
I am try to us JavaScript to validate a user input. but i am try to get it to only allow numbers. i have found one way to do it but it will be very repetitive and was wondering if there is a better way to go at this. you can see the live code here: http://metrikcorp.com/test/rate/index.php function validateForm() { var x = document.forms["Rating"]["Number"].value; if (x == "" || x >= 6 || x == 0) { document.getElementById("ERROR").innerHTML="Please Enter A Rating 1(bad) , 5(goo
6 Respostas
+ 4
Thanks alexyork
That way was a great solution. Very simple just what i was looking for!
+ 2
instead of (if or) you can check the data type of x with typeof x if x is a number it will return number all you need to do is check if x == 'number' else alert user .
var valtypex = typeof x;
if (valtypex != 'number') {
document.getElementById("ERROR").innerHTML="Please Enter A Number";
return false;
}
+ 2
in general, in html added a new input type - number. in this input you can only enter numbers
<input type="number">
0
maybe try a Math.floor(). Example : Math.floor(3.17463) >> 3
0
no problems bro)
0
if you want to go another route, better for all cases of input (strings that are numbers, etc) try RegEx!
if(x.test(/^(0|[1-9][0-9]*)$/)) {
// code
}