jqueryhtmlformsdynamic-class

Jquery: React to dynamic classes in forms


I have made a HTML form that is split up into sections.

I am using Jquery to add classes to the body element depending on what sections have been filled in.

By default, the body has a class of purchase-stop. When all the sections are filled in, this changes to purchase-go.

When the user clicks on the submit button, I use the following code to display a message:

$("input").on('click', '.purchase-stop', function()
{
    alert("You haven't visited all sections. Please visit them all to ensure you are happy with the choices");
});

The trouble is this will display even purchase-stop has been changed to purchase-go.

How can I get it to only display when the classes is purchase-stop?

Also, two fields on the form are mandatory. I use the following code to check if these mandatory sections are filled in:

$(".changing-room").submit(function(e)
    {
        e.preventDefault();

        var isFormValid = true;
        $("input.required").each(function()
        {
            if ($.trim($(this).val()).length === 0)
            {
                $(this).parent().addClass("error");

                isFormValid = false;
            }
            else
            {
                $(this).parent().removeClass("error");
            }
        });
        if (!isFormValid)
        {
            alert("Some fields are blank (highlighted in red). Please fill them in");
            $('input').blur();
        }

        if (isFormValid)
        {
            $('body').addClass('purchase-active');
            window.scrollTo(0, 0);
        }
        return isFormValid;

    });

But again, I only want it to run when the body class is set to purchase-go (and not purchase stop).

According to the Jquery docs, I have to get Jquery to run on a dynamic class (as purchase-go is not in the HTML on load). To do this, I have to use On() function. The on function is made up as follows:

.on("action [e.g. click]", "[trigger element]", function(event)

However, I have specified a trigger element, but it doesn't work.


Solution

  • on() doesn't work the way you think.

    $("[source].on("[action]", "[trigger element]", function(event)

    When you use on, you are binding to the source element, and the event is triggered for action when it occurs on trigger element within source.

    So in your case, you are setting up a click handler to fire when an element with the class purchase-stop which is a descendant of any input is clicked.

    You will need to do something like this:

    $('input[type="submit"]').click(function(e) {
        if ($('body').hasClass('purchase-stop')) {
            alert("You haven't visited all sections. Please visit them all to ensure you are happy with the choices");
        }
    });
    

    Though, using a class name on the body to indicate whether the form is valid is a little odd. You could add that functionality to your validation function.