简体   繁体   中英

Handle event onfocus with function .on() from JQuery

I have written a script to validate the input in the fields from my forms, and want this script start your action immediately when the field get focus. But right now, nothing is happening. This is the 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 what is wrong with my code?

Your parameters are in the wrong order:

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

should be:

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

Otherwise it's looking for a .valida event on a <focus> element, which won't find anything.

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

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

This isn't going to actually execute the code within the key press event, it's just going to add a new event handler. So each time you focus the element, you keep adding new handlers. You should probably just add the key press handler once outside of the focus handler. Separate the concerns of what you do in a key press (calculate validation) from what you do in a focus (display validation).

selector first so

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

Also: http://api.jquery.com/on/

The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names. changed for you works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM