jeudi 23 avril 2015

jQuery, function is applied x times instead of one

I want to check if all the inputs having the class "toCheck" are not empty, to do so, I'm using code found at: Checking if ALL form inputs are empty with jQuery

function formCheck(){
    var $fields = $(".toCheck");
    $fields.keypress(function() {
        var $emptyFields = $fields.filter(function() {

            // remove the $.trim if whitespace is counted as filled
            return $.trim(this.value) === "";
        });

        if (!$emptyFields.length) {
            alert("form has been filled");
        } else {
            alert("uh-oh, you forgot to fill something out");
        }
    });
}

My issue is, my inputs having "toCheck" class can be dynamically created, so I need to load formCheck() everytime I dynamically create a new "toCheck".

But then function formCheck() is applied 2 times (2 alert messages for one keypress)

Aucun commentaire:

Enregistrer un commentaire