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.
on()
doesn't work the way you think.$("[source].on("[action]", "[trigger element]", function(event)
When you use
on
, you are binding to thesource
element, and the event is triggered foraction
when it occurs ontrigger element
withinsource
.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 anyinput
isclick
ed.You will need to do something like this:
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.