Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent user from inserting characters in Text Box other than Only numbers can insert jQuery Mobile

I implemented iphone&android app in jQuery mobile.* i used **pure jQuery mobile

To enter phone `number in a text box. I used TYPE=”TEL”' this is for numaric keypad.

<input type="tel" style=" width:81%;" id="contactNumber" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset" /> 

But user can enter text also the text box which is unnecessary thing.

How can I prevent user from inserting characters other than numbers?

For mobile devices users it would be much more comfortable if the only input possibile is numeric, as they must press each button to get a number rather than a letter!

I tried adding TYPE=”TEL” TYPE=”mumber” in the input field, but it does not work to prevent.

like image 567
user1425472 Avatar asked Jul 13 '12 05:07

user1425472


2 Answers

$(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.

like image 200
Dale Avatar answered Nov 16 '22 01:11

Dale


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>
like image 30
user3570421 Avatar answered Nov 16 '22 01:11

user3570421