views:

1088

answers:

7

How can I restrict input to a text-box so that it accepts only numbers and the decimal point?

+3  A: 
form.onsubmit = function(){
    if(textarea.value.match(/^\d+(\.\d+)?$/)) return true;
    else return false;
}

Is this what you're looking for?

I hope it helps.

EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.

tau
Think this will also validate '99.23.65.86' ....But i guess the question was about validating '56987.32' with single dot.....
SpikETidE
i see the poster has since edited his/her original question. thanks for the update!
tau
Try with ^\d+(\.\d+)?$
Ben
@ben: thanks, that is even better.
tau
+1  A: 
Google a bit for 'Text Box Validation with Javascript'.... 

You will get tons of ideas....

Also see this other Stack overflow question

SpikETidE
+1  A: 

Are you looking for something like this?

   <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
  </HTML>
lak-b
You're missing the point (the decimal point)
Ben
Ben, fixed now ;)
lak-b
+1  A: 
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
    e= window.event? e.srcElement: e.target;
    while(e.value && parseFloat(e.value)+''!= e.value){
            e.value= e.value.slice(0, -1);
    }
}
kennebec
A: 

how can you restrict number inputs only on your text box? what i mean is you cannot input non numeric inputs on your text box, how can i do that?

rebisco
A: 

please explain your answer with a comment on each line.. thanks

rebisco
A: 

31 && (charCode < 48 || charCode > 57)) return false;

     return true;
  }
  //-->

This really works!

rebisco