How can I get each character added in a form field using jQuery/JavaScript -
i want show error message user, if enters more characters in text field specified , specification may change initial characters provided. along that, need process each character user enters business purposes. e.g.
let's think of credit card field. 
different credit card types have different max lengths. stop users entering more characters in field credit card type allows.
however, credit card type can detected when user provides few initial characters of credit card.
my approach here try detect credit card on every key press, , set maxlength of field according credit card type detected. if not detected, keep max length 19 (which maximum all)
what have tried
--------------------------------------------------------------------- | event | problem | | ------------------------------------------------------------------| | | change not triggered until user | | onchange | moves out of field. since need event | | | on every char entered, not helpful | |-------------------------------------------------------------------| | | gives issues when user presses key | | keydown | longer duration. characters entered multiple | | | times, event triggered once. | |-------------------------------------------------------------------| | keyup | same above. | |-------------------------------------------------------------------| | keypress | getting older value. newly added character | | | not available. hence incorrect calculation | --------------------------------------------------------------------- i have alternative of using time-out, looking better options.
my question different this one. because of above mentioned reasons.
please suggest solution this.
i think serves of cases need.
this work every time input changed. , reset value if enter more allowed length.
var limit = 10; //your input limit $(document).on('ready',function(){ var oldvalue = $( "input[type='text']" ).val(); $( "input[type='text']" ).on('keydown',function(e) { oldvalue = $( ).val(); }) $( "input[type='text']" ).on('input propertychange',function(e) { newvalue = $(this).val(); if(newvalue.length > limit){ $(this).val(oldvalue); alert('string long.'); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="text"> updated fiddle.
Comments
Post a Comment