Web Development Blog

How to run HTML5 required fields validation when submitting form with JavaScript

Problem: if you run document.formName.submit(); it does not validate required fields.
 
Solution is simple, use document.getElementById('submitB').click();* instead of document.formName.submit();
 
*'submitB' is submit button: <input type="submit" name="submitB" id="submitB" value="1" style="display:none;" /> . Hidden button.
 
Sample code: 
 
<form name="f1" id="f1">
<input type="text" name="name" id=" name " value="" required />
<input type="button" value="Submit" onclick="jsFunction();" />
<input type="hidden" name="hiddenValue" id="hiddenValue" value="" />
<input type="submit" name="SB" id="SB" value="1" style="display:none;" />
<form>
<script>
function jsFunction()
{
document.getElementById('hiddenValue').value = 1;
document.getElementById('SB').click();
}

</script> 

Associated tags:  CSS, Javascript, HTML5, Click(), Required

Add Comment:

CAPTCHA