There is a field <input class="ss" type="text"> hang an event on it:

 $(".ss").keyup(function(e){ this.value = this.value.replace(/[^0-9\.]/g, ''); }); 

As a result, when you enter a letter, you can see it for a moment, and then it is removed. How to make it not visible? Also, β€œ.” Is necessary.

    4 answers 4

    All you need is:

     <input type="number"> 


    In the event that it does not fit, the answer to eng.SO. I liked the option the most:

    <input type='text' onkeypress='validate(event)' />

    And this script:

     function validate(evt) { var theEvent = evt || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode( key ); var regex = /[0-9]|\./; if( !regex.test(key) ) { theEvent.returnValue = false; if(theEvent.preventDefault) theEvent.preventDefault(); } } 

      You can simply prevent the entry of unnecessary characters - for example, only numbers and periods:

       $(".ss").keypress(function(event){ event = event || window.event; if (event.charCode && event.charCode!=0 && event.charCode!=46 && (event.charCode < 48 || event.charCode > 57) ) return false; }); 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input class="ss" type="text"> 

      • dot or comma cannot be. - Sasha Omelchenko
      • @SashaOmelchenko well, all the desired characters can be added. edited for numbers and points - lexxl

       $('input').on('keydown', function(e){ if(e.key.length == 1 && e.key.match(/[^0-9'".]/)){ return false; }; }) 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input/> 

        Unfortunately I can not write comments, so I will write here. If you use jquery, why not use a mask on the field? jQuery Mask

        • There are masks everywhere, I just need to enter numbers with a single point. - Oma