Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Textfield Input to digits only

I've searched Google, but all the solutions I could find were really complicated and long. What I need is to limit the input of a textfield in a survey I'm making to digits only. What is the quickest and cleanest way to do this?

(I'm using HTML 4.01 strict and ECMAScript)

Thanks in advance.

like image 731
Hussain Avatar asked Feb 28 '23 19:02

Hussain


1 Answers

The quickest:

<input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">

That won't stop people from pasting things in with their mouse, so an onchange and onclick are probably desirable, too.

The cleanest (or at least a clean way to do it):

function forceNumeric() {
    this.value = this.value.replace(/\D/g, '');
}

If you're using a JS framework, give all your numeral-only inputs a class that indicates the fact (class="numeric" or something like that), and add forceNumeric as a callback for keyup, change, and click to any input element with that class:

$('.numeric').keyup(forceNumeric).change(forceNumeric).click(forceNumeric);

If you're using straight JS (I'd recommend not using straight JS), either use element.addEventListener, or onkeyup, onchange, and onclick.

like image 178
pib Avatar answered Mar 08 '23 13:03

pib