我使用以下脚本来更改input
元素的HTML5 required
属性。我想知道是否有办法修改此脚本以使其也可以在 Safari 浏览器中工作,因为 Safari 不支持此属性。
这是脚本:
$(document).ready(function() {
$_POST = array();
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field can't be blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
你也可以这样做:
var valid = true;
$('input[required]').each(function() {
if (this.value == '') {
// Alert or message to let them know
valid = false;
return false; // stop on first error, or remove this and it'll go through all of them.
}
});
if (valid === false) {
return false;
}
在这里查看此页面。它包含一个黑客解决方案,应该添加所需的功能
http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
您需要
在表单提交中使用事件处理程序自行运行检查。在该处理程序中,您自己运行检查,如果失败,则显示任何错误消息并使用 preventDefault
或 return false
阻止提交。
可以在这里找到一个例子,但正如它所指出的,如果你使用checkValidity作为检查表单的方法,你需要小心。