Consider the following code:
$("button[type='submit']").click(function(e){
if($(this).closest("form").checkValidity()) {
$(this).closest("form").reportValidity();
}
e.preventDefault();
alert("Never happens!!!");
});
If the input data is valid and then I press the submit button, the php form is submitted without letting e.preventDefault(); and alert("Never happens!!!"); to get executed. I suspect this happens because checkValidity and reportValidity return true, which acts as a return true; statement.
Consider this code:
$("button[type='submit']").click(function(e){
e.preventDefault();
alert("Does happen!!!");
});
This time I see the alert, meaning preventDefault stopped the form from being submitted. What is strange to me even if checkValidity and reportValidity return true, how can they act as return statement for the jquery click function?
It should be noted that the following approach doesn't work either:
$("button[type='submit']").click(function(e){
e.preventDefault();
if($(this).closest("form").checkValidity()) {
$(this).closest("form").reportValidity();
}
alert("Never happens!!!");
});
I think preventDefault prevents checkValidity and reportValidity to work properly and forces them to return false, which somehow acts as return false; statement causing the alert to not get executed.
Another possible explanation could be that calling either checkValidity or reportValidity causes the form to get submitted. I don't know why would that be the case.
Please give an explanation with reference to official documentation.
checkValidity()andreportValidity()are not methods of a jQuery object. You need to call them on the underlyingformElement object instead.It also seems from the context that the logic in the
ifcondition needs to be inverted so that thereportValidity()is called only when the form is invalid - along with thee.preventDefault()to stop the actual form submission.That being said, your JS code is completely redundant as you get this exact behaviour for free by default when you apply the
requiredattribute to any control within the form: