Gops AB Gops AB - 6 months ago 70
jQuery Question

Allow only numbers in Input field IOS

Ok Well. I want to restrict input field to accept only numbers with maxlength 5 characters.

My Try:

HTML

<input type="number" maxlength="5" onKeyDown="numbersOnly(event);/>
<input type="text" pattern= "[0-9]" onKeyDown="numbersOnly(event);/>


Javascript

function numbersOnly(event,length)
{
return event.ctrlKey || event.altKey
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46)
|| (event.keyCode>47)&&(event.keyCode<=57) ;
}


All works in firefox. But when i check with safari ipad, it accepts special characters like ()@!#$&. I used alert function for debugging. It returns same keyCode for @ and 2 , 3 and # and so on. I tried keyUp,keyPress events and event.charCode,event.which,event.key. Nothing works

So how to differentiate it and i need support for backspace , enter , delete, arrow keys also.

Answer

I've made this once and haven't been able to break it. Tested on iPad.

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

This also accounts for copy/paste and drag and drop text, which people often forget. You can add the max-length to the onchange.

Comments