Reputation: 3318
I would like to display the html 5 validation message manually (i.e. via code). According to my understanding, there is no direct way to invoke this message. However, we can bring it via submit button click.
I tried to bring the validation message (if the field is invalid) when you click on the html body:
// if url is invalid, display the error message.
if(!$('#theurl')[0].checkValidity()){
console.log('Button Click');
$('#btn').click();
}
Here is the jsfiddle for the same. Unfortunately, the above code is getting crashed. I have no idea why. Instead, if you click on the fake button manually it works fine.
Please help me to accomplish this.
Upvotes: 0
Views: 988
Reputation: 6344
The problem is that your Click function is taking the parameter 'e', but you're looking for the parameter "event".
$('body').click(function(e){
The call
$(event.target)
Change it to 'e.target' and it works:
Also, the checkValidity
function is called from the form, not from the individual items within the form. So, if you call the checkValidity function like this:
document.forms[0].checkValidity()
it will stop crashing for that reason.
Upvotes: 4
Reputation: 3599
In your jsfiddle, the code on line 22 is causing an infinite loop, which ends up causing the script to crash:
$('#btn').click();
If you comment out that line it no longer crashes. Triggering a click on the button like you are doing is also causing another click to be triggered on the body element.
To see what I mean, comment that line out, put a bad url in the form and click on the body. Each click writes a message to the console.
Upvotes: 0
Reputation: 646
Try this:
<form id="formId">
...
</form>
$('body').click(function(e){
// ignore, if clicked on the url
if ($(event.target).closest('#theurl').length) {
return;
}
// ignore, if clicked on the email
if ($(event.target).closest('#theemail').length) {
return;
}
// ignore, if clicked on the button
if ($(event.target).closest('#btn').length) {
return;
}
// if url is invalid, display the error message.
if(!$('#formId')[0].theurl.checkValidity()){
console.log('Button Click');
$('#btn').click();
}
});
Upvotes: -1