Prevent special characters on a tel input on mobile?

时间:2015-11-12 11:07:05

标签: jquery forms mobile input keyboard

I'm currently working on a form for a website and have found that despite using jQuery to prevent special characters in inputs which are 'type="tel"', you can still enter # and * characters from the mobile keyboard.

We are using the following jQuery to prevent special characters which is working on desktop:

    $(".number-only").keydown(function (e) {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
         // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
         // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }

    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
}); 

The form input has the following html:

<input type="tel" name="income" id="income" placeholder="E.g 10000" class="money number-only" pattern="[0-9]*" required>

Is there something more that the code needs, or does anyone know a way these keys can be prevented? Maybe they have their own keycode?

1 个答案:

答案 0 :(得分:0)

Are you sure you are getting the correct keycode in mobile? Have you tried printing it?

The standard, cross-browser, way to use jQuery to retrieve they keycode would be event.which. Refer to this answer.