javascript - 在 jQuery 中引导表单验证而不是纯 JavaScript?
问题描述
我在 Bootstrap 上找到了这个来使用 Bootstrap 表单验证。当其余的 Bootstrap 脚本都在 jQuery 中时,为什么示例使用纯 JavaScript 而不是 jQuery?
这怎么能用 jQuery 来完成?
https://getbootstrap.com/docs/4.0/components/forms/#validation
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
解决方案
$(document).ready(function(){
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
$(this).addClass('was-validated');
});
});
推荐阅读
- qt5 - 为什么 Qt5 中的 GUI 组件在不同分辨率的系统上部署时显示不同的大小
- javascript - 如何使用 es6 import 而不是 require?
- angular - 如何根据文本框的输入生成表格的动态行
- deep-learning - CNN中多个卷积层的效果
- angular - 订阅 FormBuilder valueChanges 时,使用 debounceTime 和 distinctUntilChanged 不起作用
- django - 如何使用 form.py 在模型中创建具有值的动态表单?
- javascript - 将文本转换为 HTML
- python - LSTMBlockFusedCell 不支持使用 outputprojectionwrapper
- javascript - 在 Web 应用程序的 JavaScript 中获取下拉值
- java - 在 Java 中使用 Polarion API 删除 OSLC 链接