简体   繁体   中英

Show alert on class change

I've been busy for some time now and can't seem to get this one. It should be really simple (I guess).

I have a form on my site with ID #form-custom . When you click on the submit button and some fields are not correct, it will display an error message and a class will be added to the form, class .error .

What I am trying to do is add an eventlistener or something else that displays an alert when the class of #form-custom changes to id="form-custom" class="error" .

So far I have tried these codes:

document.getElementById("form-custom").addEventListener("click", classchange);
    function classchange() {
        if document.hasClass.("error");
        alert("boe");
    }

and

if ($("#form-custom").hasClass('error')) {
            alert('boe.');
        });

and

$(document).ready(function(){

    $('form#form-custom').click(function(){    
        if ($(this).hasClass('error')) {
            alert('boe.');
        }
    });
}

And some variations of these codes. But non do what I would like them to do...

Could some one help me out?

Form submit should be the event that should work for your situation

$('#form-custom').on("submit", function()
{
     if($(this).hasClass("error"))
     {
         alert("Validation fail message");
         return false;
     }

     // submit form

});

You could use a MutationObserver
I would use something like this:

$("#form-custom").on("submit",function(){
    var me = $(this);
    // wait for the other onSubmit to set class
    setTimeout(function(){
        if(me.hasClass("error")) {
            alert("error")
        }
    });
});

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