0

Currently i am working on jquery validation. here I have two text field where the user can enter only number if user trying to enter by mistaken alphabets it should say digit only.

With my current code this is working perfectly fine but the text is not clearing properly.

here is the jquery code

 $('.txt_CC').on('change',function(e){

        var len = $('#txt_CC').val().length;
        if(len == 1){
            $('.cc_field').val( '00' + $('.cc_field').val());
        }else if(len == 2){
        $('.cc_field').val('0'+ $('.cc_field').val() );
        }else if(len == 3){
        }
    }); 

  $('.txt_CC').keypress(function(e){
         if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                //display error message
                $('.txt_CC').val('');
                    alert("Digit only");
                }
        });  

Please suggest me whether my code is correct

Here is the fiddle link for the html

Thanks in advance

shreesha
  • 1,811
  • 2
  • 21
  • 30
Mr.M
  • 1,472
  • 3
  • 29
  • 76

2 Answers2

3

DEMO

You can do e.preventDefault() if it was a character by preventing text to be entered in it instead of clearing. For ex:

$('.txt_CC').keypress(function(e){
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
           e.preventDefault();
           alert("Digit only");
    }
});

Update

Just add phone number elements class too into keypress event as below:

$('.txt_CC,.pn_field').keypress(function(e){
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
               e.preventDefault();
               alert("Digit only");
    }
});

DEMO

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
2

You are using keypress change for keyup. onKeyPress Vs. onKeyUp and onKeyDown

Community
  • 1
  • 1
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42