javascript - validation script losing characters -
the script below should validate user input each typed character @ once, it's losing characters, , it's character after symbol (ex.: if type 14121982
date field, 14/_2/_9822
in textfield, , 14/_2/_982
internally). also, difference between content of textfield , content intenal variable issue.
jsfiddle
http://jsfiddle.net/klebermo/f8u4c/41/
code
var counter; var tam; var str; var regex; $('.valida').each(function(){ $(this).on('focus', function(e){ regex = $(this).attr('pattern'); counter = 0; tam = size_of(regex); str = generate_string(regex, tam); $(this).val(str); }); $(this).on('keypress', function(e){ var tecla = e.which; var tecla2 = string.fromcharcode(tecla); var t = type_of(regex, counter); if(typeof tecla == t) { str = replaceat(str, counter, tecla2); //counter++; } else { if(t != 'number' && t != 'string') { str = replaceat(str, counter, t); counter++; } } counter++; result = $("<div>"); result.append( "counter = "+counter+"<br>" ); result.append( "tecla2 = "+tecla2+"<br>" ); result.append( "typeof tecla2 = "+typeof tecla+"<br>" ); result.append( "typeof t = "+t+"<br>" ); result.append( "str = "+str+"<br>" ); $("#result").empty().append(result); $(this).val(str); }); });
anyone can see what's wrong here?
after more tryouts, working code:
jsfiddle
http://jsfiddle.net/klebermo/f8u4c/78/
code
$('.valida').each(function(){ $(this).on('focus', function(e){ regex = $(this).attr('pattern'); counter = 0; tam = size_of(regex); str = generate_string(regex, tam); $(this).val(str); }); $(this).on('keypress', function(e){ e.preventdefault(); var tecla = e.which; if(tecla >= 48 && tecla <= 57) var tecla2 = tecla - 48; else var tecla2 = string.fromcharcode(tecla); result = $("<div>"); result.append( "tecla = "+tecla+"<br>" ); var t = type_of(regex, counter); if(counter < tam) { if(t != 'number' && t != 'string') { str = replaceat(str, counter, t); counter++; } t = type_of(regex, counter); if(typeof tecla2 == t) { result.append( "tecla2 = "+tecla2+"<br>" ); str = replaceat(str, counter, tecla2); counter++; } } result.append( "counter = "+counter+"<br>" ); $("#result").empty().append(result); $(this).val(str); }); });
Comments
Post a Comment