replace input number to text

by Laurens Maneschijn

HTML

<input type="number" value="" />

<p>
    This <code>&lt;input type="number"/&gt;</code> defaults to type="number", 
    but changes to type="text" if you type non-numerical characters.
</p>
<p>
    Handy for fields (like housenumber) that 99% of the time expect numbers and get a nice numerical interface, 
    but still allow for that 1% to enter text if you really need to.<br/>
    <small>(NB: if you initialize with a value="x" make sure to change to type="text" on init too)</small><br/>
</p>
<p>
    Note: on mobile devices you will probably get a numerical-only keyboard and it will be hard if not impossible to trigger a "wordcharacter" keyup event, so mobile will still be limited to numbers only if it only changes on "wordcharacter" keyevents.<br/>
    However, if you cnange it on keyup of anything not within 0-9 range you usually have other keys like ".- " on the keypad that might trigger a change from number to text.
</p>

JavaScript

$(document).on('keyup','input[type=number]',function(e){
//  console.log(e.keyCode);
    if(e.keyCode < 48 && e.keyCode <= 57){ // 48-58 : 0-9 ; all NON numerical 0-9 characters
        $(this).prop('type','text');
    }
//  if(e.keyCode >= 65 && e.keyCode <= 90){	// 65-90 : a-z
//      $(this).prop('type','text');
//  }
})