Page 1 of 1

Limit Input to Only Numeric

Posted: Tue Feb 15, 2022 11:51 am
by pmjd
Hello,

I've been using the new attributes maxlength option to limit the number of characters that can be inputted to a text object, and it works well.
I'd also like to limit it to only accepting numbers and backspace.

I've tried using the code at https://www.dofactory.com/html/input-at ... idyouknow2 by adding the following to the onkeydown event (both with and without the original double quotes and also encasing it within a function)

Code: Select all

return (event.charCode != 8 && event.charCode == 0 || (event.charCode >= 48 && event.charCode <= 57))
but it doesn't seem to work.

Can anyone suggest a way to get it to work?

Thanks,
Paul

Re: Limit Input to Only Numeric

Posted: Tue Feb 15, 2022 12:05 pm
by kev1n
Hi Paul,

Can't you use a Number Input Type?

Re: Limit Input to Only Numeric

Posted: Tue Feb 15, 2022 12:18 pm
by pmjd
Unfortunately the number type doesn't stop any non-numeric input, it allows it and then defaults to 0 after saving.

Also the number input type does not allow the maxlength attribute to function. Maxlength is only supported in password, search, tel, text, and url input types.
https://developer.mozilla.org/en-US/doc ... -maxlength

Re: Limit Input to Only Numeric

Posted: Tue Feb 15, 2022 12:18 pm
by kev1n
Otherwise, try:

Code: Select all

var charCode = (event.which) ? event.which : event.keyCode
return !(charCode < 48 || charCode > 57) || charCode == 8

Re: Limit Input to Only Numeric

Posted: Tue Feb 15, 2022 12:20 pm
by pmjd
Great, your code works. Thank you very much :)