0
  • I have a input box and need to accept just numbers.

  • I use javascript and it works fine but the problem : when the box is empty or deleting numbers it returns false and the box color get red.

Here is the codes:

<input id="amount" type="number" size="7" name="amount" onkeypress='return isNumberKey(event)' required/>


<script type="text/javascript">
    function isNumberKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
</script>
2

2 Answers 2

2

check it this validation code : http://jsbin.com/ImIruPEf/1/edit

$(document).ready(function(){
  $("#Submit").click(function(e){
     var isNumber =   IsNumberOnly('input#Age');
    if(!isNumber)
    {
      e.preventDefault();
      $("#ErrorMessage").text('Invalid value. Please enter numeric value.');
    }
    else
    {
       $("#ErrorMessage").text('Success.');
    }
  });
});

function IsNumberOnly(element) {    
    var value = $(element).val();
    var regExp = "^\\d+$";
    return value.match(regExp); 
}
Sign up to request clarification or add additional context in comments.

Comments

0
<script type="text/javascript">
function demoMatchClick() {
 var re = new RegExp("^[0-9]+$");
 var val=document.GetelementByID("amount").value;
   if (val.match(re)) {
      alert("Successful match");return true;
   } else {
      alert("No match"); return false;
   }
 }
 </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.