1

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?

Steggie
  • 525
  • 8
  • 31
  • Have you tried this? http://stackoverflow.com/questions/1950038/jquery-fire-event-if-css-class-changed – Mario Plantosar Jun 10 '16 at 12:47
  • 1
    `$(this).addClass('invalid'); $("#form-custom").trigger('cssClassChanged') $(".invalid").bind('cssClassChanged', data, function(){ alert("boe") });` I don't really get that answer, could you please review my code? – Steggie Jun 10 '16 at 12:50

2 Answers2

1

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

});
Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105
1

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")
        }
    });
});
Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25
  • Thanks for the code. But no go for me... It didn't work. Could I modify this code in such away that it will always give an alert, just to see if this code works? Like change the status of the "submit" to something else? – Steggie Jun 10 '16 at 13:02
  • remove the if -clause... you need to click on the submit-button or press enter in an input inside the form. Also i expect, that you already added the function to add the class to the form if some fields are invalid. – Mephiztopheles Jun 10 '16 at 13:28