I have tried following code for make the required field to notify the required field but its not working in safari browser. Code:
<form action="" method="POST"> <input required />Your name: <br /> <input type="submit" /> </form>
Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/
Can you let me know the javascript code or any workarround? am new in javascript
Thanks
If the input elements aren't inside a form tag then HTML5 required attribute will fail to work. So always put input tags inside a form along with the form encapsulation itself.
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
HTML | <input> required Attribute The HTML required Attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the Form. This attribute works with other types of input like radio, checkbox, number, text, etc.
Safari, up to version 10.1 from Mar 26, 2017, doesn't support this attribute, you need to use JavaScript.
This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
HTML:
<form action="" method="post" id="formID"> <label>Your name: <input required></label><br> <label>Your age: <input required></label><br> <input type="submit"> </form>
JavaScript:
var form = document.getElementById('formID'); // form has to have ID: <form id="formID"> form.noValidate = true; form.addEventListener('submit', function(event) { // listen for form submitting if (!event.target.checkValidity()) { event.preventDefault(); // dismiss the default functionality alert('Please, fill the form'); // error message } }, false);
You can replace the alert with some kind of less ugly warning, like show a DIV with error message:
document.getElementById('errorMessageDiv').classList.remove("hidden");
and in CSS:
.hidden { display: none; }
and in HTML:
<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>
The only drawback to this approach is it doesn't handle the exact input that needs to be filled. It would require a loop accross all inputs in the form and checking the value (and better, check for "required" attribute presence).
The loop may look like this:
var elems = form.querySelectorAll("input,textarea,select"); for (var i = 0; i < elems.length; i++) { if (elems[i].required && elems[i].value.length === 0) { alert('Please, fill the form'); // error message break; // show error message only once } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With