javascript - Handle event onfocus with function .on() from JQuery -


i have written script validate input in fields forms, , want script start action when field focus. right now, nothing happening. jsfiddle example:

http://jsfiddle.net/klebermo/f8u4c/1/

code:

$(document).on('.valida', 'focus', function(){     $("#result").append("<p>starting validation</p>");     var regex = $(this).attr('pattern');      var counter = 0;     var tam = size_of(regex);     var str = generate_string(regex, tam);      $(this).val(str);      $("#result").append("<p>counter = "+counter+"</p>");     $("#result").append("<p>str = "+str+"</p>");      $(this).keypress(function(event){         var tecla = e.which;          if(typeof tecla == type_of(regex, counter)){             str[counter] = tecla;             if(typeof tecla == 'number' || typeof tecla == 'string')                 counter++;             else                 counter += 2;         }          $("#result").append("<p>counter = "+counter+"</p>");         $("#result").append("<p>str = "+str+"</p>");          $(this).val(str);     }); }); 

anyone knows wrong code?

your parameters in wrong order:

$(document).on('.valida', 'focus', function(){ 

should be:

$(document).on('focus', '.valida', function(){ 

otherwise it's looking .valida event on <focus> element, won't find anything.

also, you're re-binding key press event every time focus element:

$(this).keypress(function(event){ 

this isn't going execute code within key press event, it's going add new event handler. each time focus element, keep adding new handlers. should add key press handler once outside of focus handler. separate concerns of in key press (calculate validation) in focus (display validation).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -