Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

html - Required Attribute Not work in Safari Browser

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

question from:https://stackoverflow.com/questions/23261301/required-attribute-not-work-in-safari-browser

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...