/ Published in: JavaScript
This snippet contains a text input field called 'abc' and we calling the checkNum function as the onclick action of a button 'btn'
Expand |
Embed | Plain Text
function checkNum(){ var inputBox = document.getElementById('abc'); if(inputBox.value.length!='0'){ var j=0; var run = false; for(j=0; j<inputBox.value.length; j++){ var char=inputBox.value.charAt(j); if(inputBox.value.charAt(j)>='0' && inputBox.value.charAt(j)<='9'){ run = true; } else{ run = false; alert("Q# can only be a numeric value"); document.getElementById('abc').focus(); document.getElementById('abc').value=""; break; } } if(run){ alert("The field has been successfully validated!"); } } else if(inputBox.value.length == '0'){ alert("Please enter a Q#"); document.getElementById('abc').focus(); } }
Comments
Subscribe to comments
You need to login to post a comment.

you could also just run a regexp test
var onlyNums = /[^0-9]/g;
if (onlyNums.test("asdf90")) { alert("numbers only"); }
thanks MMDeveloper.
Yours is a much better way to do it.
Cheers :)
looking at this again, my input would be an integer validation, if you wanted to allow a floating point number as well, you could do something like [code] textBoxValue = "asdf 903.31"; floated = parseFloat(textBoxValue);
if (textBoxValue != floated) { alert("enter a number"); } else {} [/code] that will parseFloat the value (convert it to a floating point number) which should automatically strip out other characters. If you compare the parseFloat'd value with the original value and they match, then the original input was a number, if the 2 values do not match, then some non-numbers (or multiple decimals) were input.