Jor*_*lla 6 html javascript validation jquery
场景:我有一个带有多个手风琴(可扩展的 div)的表单,每个手风琴都有一些必填字段,用户可以自由折叠或展开它们,因此,在某些情况下,有未填写的强制隐藏字段(因为折叠)提交表单时。
问题:在 Chrome 中,用户不会出现任何错误,只有在控制台中您才能阅读:
name='' 的无效表单控件不可聚焦。
我已经找到了很多关于这个问题的答案。我完全知道为什么会发生这种情况,但我没有找到任何解决我的问题的方法。
我尝试过的:在提交表单之前,展开所有手风琴以显示所有必填字段,这样我就可以让浏览器聚焦元素并显示必填字段消息(请参阅更新)
所需的解决方案:识别需要内容的必填字段的 id,以扩展其手风琴容器并聚焦该字段
更新:发现通过 javascript 扩展所有可折叠 div 的解决方案并非在所有情况下都有效,因此不是解决方案。
问题:有什么方法可以在验证前显示该字段?如果没有...我可以在提交表单时关注或识别隐藏的必填字段吗?
我个人会同意 Niet the Dark Absol关于在更改部分和显示警告标志时检查字段的建议(我认为这会提供更好的用户体验)。
但是如果您想继续检查表单提交,有一种方法可以通过使用 JavaScript来诱使浏览器执行您想要的操作。浏览器识别并突出显示页面验证时可见的第一个无效字段(对于 IE 和 FF,它将突出显示所有可见的无效字段);因此,在表单验证发生之前,您需要运行快速检查并打开包含第一个无效字段的手风琴部分。
关键是在 HTML5 验证发生之前运行该检查。这意味着这onsubmit
还不够好,因为浏览器会在submit
事件发生之前进行验证。您需要在单击提交按钮/图像时运行代码,因为该click
事件发生在浏览器验证字段之前。
您没有指定它是用于 jQuery UI 还是 Bootstrap,因此这里是两者的示例(代码类似,只是更改了处理打开/关闭手风琴的方式):
您可以在此 JSFiddle 上看到 jQuery UI 的工作演示:http : //jsfiddle.net/ma8v32ug/1/。JavaScript 检查将是这样的:
// save the accordion in a variable as you'll need it later
$accordion = $("#accordion").accordion();
// when the submit is clicked
$("#myForm input[type='submit']").on("click", function(event) {
// traverse all the required elements looking for an empty one
$("#myForm input[required='required']").each(function() {
// if the value is empty, that means that is invalid
if ($(this).val() == "") {
// find the index of the closest h3 (divide by 2 because jQuery UI accordion goes in pairs h3-div. A bit hacky, sorry)
var item = $(this).closest(".ui-accordion-content").prev().index() / 2;
// open that accordion section that contains the required field
$accordion.accordion("option","active", item);
// stop scrolling through the required elements
return false;
}
});
});
Run Code Online (Sandbox Code Playgroud)
注意:这对 Bootstrap 3.3.4 版有效。我没有签入旧版本或新版本。
Bootstrap 需要考虑的一件重要事情是您不能使用该.collapse({toggle: true})
功能,因为动画花费的时间比浏览器验证表单所需的时间多,并且结果将出乎意料(通常,浏览器会停止动画指向错误,它不会是您想要的字段)。
一个解决方案是在没有动画的情况下进行切换,只需更改.in
面板中的类,并调整目标面板高度。最后,该函数看起来非常接近 jQuery UI 的函数,只是略有变化:
// when the submit is clicked
$("#myForm input[type='submit']").on("click", function(event) {
// traverse all the required elements looking for an empty one
$("#myForm input[required='required']").each(function() {
// if the value is empty, that means that is invalid
if ($(this).val() == "") {
// hide the currently open accordion and open the one with the invalid field
$(".panel-collapse.in").removeClass("in");
$(this).closest(".panel-collapse").addClass("in").css("height","auto");
// stop scrolling through the required elements
return false;
}
});
});
Run Code Online (Sandbox Code Playgroud)
你可以看到它在这个 JSFiddle 上工作:http : //jsfiddle.net/ma8v32ug/2/
归档时间: |
|
查看次数: |
3878 次 |
最近记录: |