Thursday, September 1, 2016

Allowing numeric characters only in Input text using JavaScript


We can always restrict user from entering non numeric / special characters in  input field by using JavaScript

For that to work you have to add the af:clientListener tag to your Input text component – af:inputText – to call out to JavaScript when users type in the input field

Input text code looks as shown below


<af:inputText label="Numbers:" id="it1">

            <af:clientListener method="processKeyDown" type="keyDown"/>
            <af:clientListener method="processKeyUp" type="keyUp"/>
   </af:inputText>

The JavaScript code that you use in af:resource tag to filter character inputs or numeric inputs is shown below


            var shiftDown = false;
             var ctrlDown = false;
             function processKeyUp (evt) {
                var key = evt.getKeyCode();
                if (key == 16) {
                  shiftDown = false;
                }
              }
             function processKeyDown (evt) {
                var key = evt.getKeyCode();
                if(key == 17){
                    ctrlDown = true;
                }
                if (key == 16) {
                  shiftDown = true;
                }
                //Allow: ctrl+c and ctrl+v
                if ((ctrlDown == true &amp;&amp; key == 86) || (ctrlDown == true &amp;&amp; key == 67)) {
                    // let it happen, don't do anything
                    ctrlDown = false;
                    return;
                }
                // Allow: backspace, delete, tab, escape, enter and .
                if (key == 8 || key == 9 || key == 27 || key == 13 ||
                // Allow: home, end, left, right
                (key >= 35 &amp;&amp; key &lt; 41)){
                  // let it happen, don't do anything
                  return;
                } else {
                  // If non numeric or shift is pressed then stop the keypress
                  if (shiftDown || (key &lt; 48 || key > 57) &amp;&amp; (key &lt; 96 || key > 105)) {
                      evt.cancel();
                  }
                }

              }

You can always find out JavaScript event keycode using http://keycode.info/ and press any key to get its keycode.


No comments:

Post a Comment