To check whether a field is numeric by using JavaScript


/ Published in: JavaScript
Save to your folder(s)

This snippet contains a text input field called 'abc' and we calling the checkNum function as the onclick action of a button 'btn'


Copy this code and paste it in your HTML
  1. function checkNum(){
  2.  
  3. var inputBox = document.getElementById('abc');
  4. if(inputBox.value.length!='0'){
  5. var j=0;
  6. var run = false;
  7. for(j=0; j<inputBox.value.length; j++){
  8. var char=inputBox.value.charAt(j);
  9.  
  10. if(inputBox.value.charAt(j)>='0' && inputBox.value.charAt(j)<='9'){
  11. run = true;
  12. }
  13. else{
  14. run = false;
  15. alert("Q# can only be a numeric value");
  16. document.getElementById('abc').focus();
  17. document.getElementById('abc').value="";
  18. break;
  19. }
  20. }
  21. if(run){
  22.  
  23. alert("The field has been successfully validated!");
  24. }
  25.  
  26.  
  27. }
  28. else if(inputBox.value.length == '0'){
  29. alert("Please enter a Q#");
  30. document.getElementById('abc').focus();
  31. }
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.