Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on("focus",[...]) doing process several times

Tags:

jquery

dynamic

I had just started using $.on() for a dynamical table for collect passenger personal data. This is the typical that you have to hit an add button to add a new row at the end of the table for more passengers.

I have to validate the child ID (RUT) it's works great, but when the validation fails I show an alert, to tell the user that the data is incorrect so, first time it looks ok, but if the user fails again, it shows 2 alerts, then 3,4,... and so on as the user continues his struggle for enter an invalid ID.

I would be very happy if anyone can help, to correct this behavior achieving show only one alert per fails. Clicking "ok" five times is very annoying, and could be a reason for the project to be left behind.

This is the code I use:

    $("#tabdata").on("focus",".rut",function(){
    $(this).css("border","1px solid lightSkyBlue");
    });
$("#tabdata").on("focus",".rut",function(){
    $(this).blur(function(e){   
        var rut = $(this).val();
        var rutarr = rut.split("-");
        if (rutarr.length==1 || dv(rutarr[0].toLowerCase())!=rutarr[1].toLowerCase()){
        //ver si el rut esta mal escrito, sin guion split no separara nada.
        $(this).css("border","1px solid Red");
        alert("EPA!!!, no tan rapido, el Rut ingresado no es valido, por favor revisa bien.");

        }else{
        $(this).css("border","1px solid Green");

        }
    });
});

and here is the page for you to see this epic fail of mine.

like image 281
Marcos Vargas Moran Avatar asked Jan 19 '26 23:01

Marcos Vargas Moran


1 Answers

This is happening because you are binding an event handler within another event handler. Each time a .rut element is focused another blur event handler is attached to the element. Remove the blur event hanler from the focus event handler and all will be well:

$("#tabdata").on("focus",".rut",function(){
    $(this).css("border","1px solid lightSkyBlue");
}).on("blur",".rut", function(e){   
    var rut    = $(this).val(),
        rutarr = rut.split("-");
    if (rutarr.length == 1 || dv(rutarr[0].toLowerCase()) != rutarr[1].toLowerCase()){
    //ver si el rut esta mal escrito, sin guion split no separara nada.
        $(this).css("border","1px solid Red");
        alert("EPA!!!, no tan rapido, el Rut ingresado no es valido, por favor revisa bien.");

    } else {
        $(this).css("border","1px solid Green");

    }
});
like image 71
Jasper Avatar answered Jan 21 '26 13:01

Jasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!