简体   繁体   中英

keydown event - key pressed on different systems

I have a number input, which I want user to by unable to insert any non-digit characters. We have attempted this in a number of ways:

We started with removing all non-numeric characters on blur:

$(my_input).blur(function() {
  $(this).val($(this).val().replace(/[^\d]/, '')
}

The problem with the code above is that number field's val function returns empty string if the input is invalid. We definitively want a number field as our website is to be used on mobiles.

The option which I would prefer is to use keydown event:

$(my_input).keydown(function(e) {
        if (e.shiftKey === true ) {
            if (e.which == 9) {
                return true;
            }
            return false;
        }
        if (e.which > 57) {
            return false;
        }
        if (e.which==32) {
            return false;
        }
        return true;
    });  

The above works almost as a charm. The problems are:

  1. numeric keyboard not included in a range - this can be however easily fixed and is not a subject of this question.

  2. For unknown to me reasons js on iOS is using different key codes, hence this is not working on huge part of mobile phones, iPads etc.. This is a deal breaker.

So the question - is there any way to determine which key was actually pressed with an keydown event. I have seen number of similar questions, none of them however covered those iOS differences. I've noticed that event has a 'key' property, however I am not sure how reliable this property is.

EDIT: I fell on this post which might be a neat way to solve your problem: JavaScript: Avoiding hardcoded keycodes

It would boil down to

var digitCodes = "0123456789".split('').map(function (x) { return x.charCodeAt(0); });

There might be a better way to do this but you could detect if the device is running iOS (cf Detect if device is iOS ) and use the appropriate keycodes (cf http://notes.ericjiang.com/posts/333 ).

var digitCodes;
if (isiOS()) {
    digitCodes = keycodes.ios;
}
else {
    digitCodes = keycodes.default;
}

if (digitCodes.indexof(e.which) != -1) {
    ...
}

Something like that...

You can try it this way

sample text box

<input type="text" name="sample" id="sample" onkeyup="positiveNumericOnly(this);" />

JS Code

function positiveNumericOnly(ele)
{
    tempVal = ele.value.replace(/[^\d]/g, "");
    if(tempVal != ele.value)
        ele.value = tempVal;
}

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