8
4

6 に答える 6

14
$(document).ready(function() {
    $('#contactNumber').keyup(function() {
        var numbers = $(this).val();
        $(this).val(numbers.replace(/\D/, ''));
    });
});

This should replace any non-digit with an empty character *as they are put in, negating the need to search for more than one non-digit at a time.

于 2012-07-13T05:40:46.380 に答える
7

None of the above worked for me but I found a solution that works perfectly for what I needed (to disallow special characters in an input field). Prevents and alerts user.

    <script>
     $("#userlogin").keypress(function(e) {
      if (String.fromCharCode(e.which).match(/[^A-Za-z0-9_ ]/)) {
        e.preventDefault();
        alert("Special characters are not allowed. Use 'A-Z', 'a-z' and '0-9'.");
       }
     });
    </script>
于 2014-04-24T19:42:28.320 に答える
1

Seen this answered before. Check out http://www.texotela.co.uk/code/jquery/numeric/

And you can simply change your class id and have this code on your page:

$(document).ready(function(){
    $(".numeric").numeric();
});

If you don't want to use jQuery, you could write your own function and call it onkeyup event

See: http://www.htmlcodetutorial.com/forms/index_famsupp_158.html

Another option is using step attribute:

http://www.w3.org/TR/html-markup/input.number.html#input.number.attrs.step.float

<input type="number" step="0.01" min="0" >
于 2012-07-13T05:38:00.393 に答える
1

type="tel" is HTML 5, and not jqueryMobile. the later devices whose browsers support HTML 5 input types render these boxes fine. But for older versions, the additional scripts need to be there. The scrips are already posted in above answers.

于 2012-09-24T10:50:43.000 に答える
0
$('#contactNumber').bind('keypress', function (event) {
        event = event || window.event; canAdd = new Boolean(false);
        canAdd = ((event.charCode > 47) && (event.charCode < 58) || (event.charCode == 32) || (event.charCode == 40) || (event.charCode == 41) || (event.charCode == 43) || (event.charCode == 45) || (event.charCode == 124));
        if (!canAdd && event.charCode)
            return false;
    }); 

But better to use HTML5 tel attrubute

于 2013-05-20T12:00:28.300 に答える
0

HTML :

 input type="tel" (keypress)="isNumberKey($event)" 

Script :

isNumberKey(evt: any) { < br >
        // to accept only numbers in contact field<br>
        if ( < br >
            (evt.key >= '0' && evt.key <= '9') || < br >
            evt.key == "Backspace" || < br >
            evt.key == "Delete" || < br >
            evt.key == "ArrowLeft" || < br >
            evt.key == "ArrowRight" < br >
        ) { < br > //"Backspace" etc for 'firefox' browser<br>
                return true; < br >
        } < br >
        return false; < br >
}
于 2018-03-16T06:05:25.947 に答える