Search code examples
javascriptprototypejs

Prototype. Restrict input to numbers


I have multiple inputs to which i am attaching event listener that listens to what key was pressed, tests it with regular expression and returns true if number and false if other charachter. The problem is that input is accepting letters even if my test function returns false.

$$(".number").each(function (element) {
  return $(element).observe("keypress", function (event) {
    return /[\d\s]/.test(String.fromCharCode(event.keyCode));
  });
});

Example on JS Bin.


Solution

  • You are using prototypeJS, which as far as I know doesn't allow to use return false to cancel event propagation and default behavior (As jQuery does). Though it has Event.stop(event) method

    $$(".number").each(function (element) {
        return $(element).observe("keypress", function (event) {
            var result = /[\d\s]/.test(String.fromCharCode(event.keyCode));
    
            if (!result) {
                Event.stop(event);
            }
        });
    });
    

    Event.stop(event)