30 June 2014

JavaScript [1] - Limiting text input to numbers only

As I have changed my professional direction a little bit, I'm finding new interesting topics to blog about. Namely, I've been moved to J2EE development project, vast mix of pure Java, Chordiant, ILOG, WAS and Oracle. Hence, I'm now focusing on code issues more than WebSphere&Security integration issues.

For the sake of continuity I'm not going to change blog name - I'm anyway "somewhere around" the original topic, and probably I will be back to it someday.

So, here's my first JavaScript hint - if you need to limit text input in your HTML form to numbers (decimals, with decimal point) only, you can do it like this:


  1. put together a nice piece of javascript validating what is being input:

  2. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script>
    $('#in').bind('input propertychange', function() {
        var text = $(this).val();
        var t2 = text.replace(/[\\A-Za-z!"£$%^&\-\)\(*+_={};:'@#~,Š\/<>\" "\?|`¬\]\[]/g,'');
        $(this).val(t2);
                                // line below is purely for presentation purposes - set value of paragraph named "result" to the valid input value
        $('#Result').text(t2); 
       
    });
    </script>
  3. test it out in a piece of complete HTML page to see how it works. important thing is you need to put the <script> part AFTER you put your input field into the document - otherwise the script won't be "bound" to the input:
<html>

<body>
<p>try the input</p>
<input type="text" id="in"><br>
<label id="Result"></label>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>

$('#in').bind('input propertychange', function() {
    var text = $(this).val();
    var t2 = text.replace(/[\\A-Za-z!"£$%^&\-\)\(*+_={};:'@#~,Š\/<>\" "\?|`¬\]\[]/g,'');
    $(this).val(t2);
$('#Result').text(t2);
 
});
</script>

</body>
</html>

Good luck! hope you will find this useful!

2 comments: