javascriptphpnumberskeycode

"Number Only" Field with Comma Separators


I am working on creating a field that is basically number only besides having comma separators inserted at the thousand, million, etc. mark.

The first issue that In appear to be running into is whether or not keycode 188 even works for allowing commas. When using the code here, I am unable to actually type a comma into the field, even though I appear to have excluded it from returning false:

function forceNumber(event){
    var keyCode = event.keyCode ? event.keyCode : event.charCode;
    if((keyCode < 48 || keyCode > 58) && keyCode != 188)
        return false;
}

Here is the script that I am using to add the comma separators, I'm not entirely sure if it is this script, the one just referenced, or how I am calling them in the PHP file that is causing it not to function. Here is the comma insertion js:

function numberWithCommas(n){
    n = n.replace(/,/g, "");
    var s=n.split('.')[1];
    (s) ? s="."+s : s="";
    n=n.split('.')[0]
    while(n.length>3){
        s=","+n.substr(n.length-3,3)+s;
        n=n.substr(0,n.length-3)
    }
    return n+s
}

And finally the PHP call:

<p>
            <label for="yearly_income"><?php _e('Yearly Income<br><i>Used to determine  fee per session</i>','mydomain') ?><br />
                <input type="number" name="yearly_income" id="yearly_income"     class="input" value="<?php echo esc_attr(stripslashes($yearly_income)); ?>" size="25"     onkeypress="return forceNumber(event);" onkeyup="this.value=numberWithCommas(this.value);"     /></label>
</p>

Any assistance on this would be wonderful. It's amazing how complex it can be to get a field to work for something like inputting the income in a way that is user readable and friendly!


Solution

  • change type="number" to type="text"

    Demo fiddle

    The browser is interpreting type="number" and making sure you can't put anything but numbers in that field thats why it goes blank.