I'm having trouble displaying html5 inline validation bubble without using submit button. I can't use jQuery, only vanilla javascript.
This is my html:
<a id="send" href="#">Send</a>
<form id="sendform" action="">
<input type="email" placeholder="E-mail" id="email-add" required>
</form>
And this is my javascript:
var btn = document.getElementById('send');
var emailField = document.getElementById('email-field');
btn.addEventListener('click',function() {
// remove validation message
emailField.setCustomValidity('');
if (!emailField.validity.valid) {
// set custom validation message
emailField.setCustomValidity('Custom error message!');
// add CSS class
emailField.className = 'invalid';
}
});
When clicking on anchor, I want to trigger validation bubble with custom message, but bubble doesn't show up. If I use submit button inside a form, bubble is there.
Here is an example: https://jsfiddle.net/esedic/rc8va4vf/
Any ideas?
The reason why the error messages are not showing is because your form is never submitted. In order to do this, you can try something like this :
https://jsfiddle.net/2gs6hx7q/6/
The html form need to be submitted via a submit button, the trick is to create a hidden submuit button which will be clicked when the a element is clicked
var btn = document.getElementById('send'); var emailField = document.getElementById('email-add'); var myForm = document.getElementById('sendform'); emailField.oninvalid = function(e) { e.target.setCustomValidity(""); if (!e.target.validity.valid) { e.target.setCustomValidity("Error message"); } }; emailField.oninput = function(e) { e.target.setCustomValidity(""); }; btn.addEventListener('click',function(e) { document.querySelector('#submitBtn').click(); });
<a id="send" href="#">Send</a> <form id="sendform" method="POST" name="sendform" onsubmit="return false;"> <input type="email" placeholder="E-mail" id="email-add" required> <input type="submit" id="submitBtn" style="display:none;"> </form>
just return true or false in the end of handler.See this link
HTML tag <a> want to add both href and onclick working
You code is working with this 1 line change.
btn.addEventListener('click',function() {
// remove validation message
emailField.setCustomValidity('');
if (!emailField.validity.valid) {
// set custom validation message
emailField.setCustomValidity('Custom error message!');
// add CSS class
emailField.className = 'invalid';
}
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.