This question deals with allowing only numeric characters to be entered in an input text field. I am needing to do the same thing, except that negative sign and decimal must be allowed. Also the solution needs to work in Mobile Safari, for iOS 6 and iOS 7.
I have tested the accepted solution which is based on checking keycodes in the keyup event handler, but this solution does not work on my iPad because it allows the following characters to be entered:
()$&@!
The code below is based on this solution:
('input.numeric').keyup(function(e) {
this.value = (this.value.replace(/[^0-9.\,-]/g, ''));
});
Although this code works well in desktop browsers that I have tested (eg Chrome), on Mobile Safari it does not seem to work very well. On iOS 5, this does allow numeric characters and the minus sign to be entered, but it results in the cursor position acting strangely with the cursor often appearing before the entered character. On iOS 6, for some reason this does not allow the minus sign to be entered, only numeric characters.
Does anyone have a solution that does work correctly on Mobile Safari. I am looking for a pure Javascript solution here, or one that depends only on jQuery. Please don't answer with "use this or that library" or make comments about Javascript validation not being safe.