简体   繁体   中英

Dynamically restrict special characters in number input on iOS

I've seen a bunch of questions that are similar to this but not quite what I am looking for... apologies if I've missed one.

So, I have a series of number inputs for an HTML app that runs in an iOS UIWebView and mobile Safari. They need to accept only numbers and not special characters or letters and must validate to a max value.

I'm currently using e.which to validate, which is working most of the time, but of course a bunch of punctuation characters (despite being different keys on iOS) report the same keycode as number keys, and I'm having trouble figuring out if I can just not allow them to be entered vs stripping them out after they've displayed in the input field.

(Irrelevant code and structure has been removed.)

<input type="number" id="input-patients" value="1600" max="10000" min="0" />
<input type="number" id="input-pct_dropout" value="16" max="100" min="0" />
<input type="number" id="input-annual_dollars" value="275" max="500" min="0" />

JavaScript:

$('.input').on('keydown', function(e){

    var charCode = (e.which) ? e.which : event.keyCode;
    if (charCode > 47 && charCode < 59 || charCode == 8){
    // here a bunch of other stuff happens
       return true;
    }
    else{
       return false;
    }
});

Can I check for special characters without having them display in the input fields first and then stripping them from the string?

Thanks in advance.

onkeyup of selected input element write event: get value from input box, then check is number? (if yes then isNAN(val) return false and stop further processing), else go for next execution which call recursive function turnToInt and set value of this input box with valid INT returned from that function;

turnToInt function : check is valid number (if yes return that number or remove last character from val and call itself for further validation finally return valid INT number);

$(".select_object").keyup(function() {
      (val = $(this).val()) && isNaN(val) && $(this).val(turnToInt(val))
    });

function turnToInt(val) {
    return isNaN(val) ? turnToInt(val.substr(0,val.length-1)) : val;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM