I\'m trying to implement html5 into a form, but I came with a problem when I submit the form through jquery and try to use the html5 \"required\" attribute.
Here is
You are right. HTML5 validation works only when submit is triggered by user. this is how it is. :(
you need write a your own custom method on submit. OR there is a good plugin you can use which validates fields according html5 attributes.
here is the plugin link
Answer from https://stackoverflow.com/a/30124479/7915308
<!DOCTYPE html>
<html>
<body>
<form name="testform" action="action_page.php">
E-mail: <input type="email" name="email" required><br/>
<a href="#" onclick="javascript:console.log(document.testform.reportValidity());return false;">Report validity</a><br/>
<a href="#" onclick="javascript:console.log(document.testform.checkValidity());return false;">Check validity</a><br/>
<a href="#" onclick="javascript:if(document.testform.reportValidity()){document.testform.submit();}return false;">Submit</a>
</form>
</body>
</html>
You could call a function instead and use that function to check if all the nodes with the required attribute have a value.
There are some plugins available to do this: http://thechangelog.com/post/1536000767/h5validate-html5-form-validation-for-jquery
Here an exemple of my personnal solution:
var form = $('#loginform');
// Trigger HTML5 validity.
var reportValidity = form[0].reportValidity();
// Then submit if form is OK.
if(reportValidity){
form.submit();
}
I did the following
<form>
...
<button type="submit" class="hide"></button>
</form>
<script>
...
$(...).find('[type="submit"]').trigger('click');
...
</script>
¡it works!
I had exactly the same problem. I had a single button that I had deliberately set NOT to be a submit because it was on first click revealing a form. On a second click of the same button $('form[name=xxx]').submit(); was firing and I found as well that the HTML5 validation doesn't work.
My trick was to add a line of code so that after my first click of this button occurs I change its type to submit dynamically.
$("#btn").attr("type","submit");
Which worked like a charm!