我创建了一个简单的表单来提交文本。 此文本输入为必填项。
但是,如果我单击“提交”按钮,即使所需的文本为空,也会发送表格。
我使用了this bootstrap example模板
// 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
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)
}())
$("#suche").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div id="karte1" class="col-md-7 order-md-1">
<form class="needs-validation" id="suche" novalidate>
<div class="mb-3">
<div class="input-group">
<input type="text" class="form-control" id="username2" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary">
submit
</button>
</div>
<div class="invalid-feedback" style="width: 100%;">
Valid text is required.
</div>
</div>
</div>
</form>
</div>
<!-- Karte1 -->
</div>
<!-- row -->
</div>
<!-- container -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
感谢您的帮助!
答案 0 :(得分:0)
您可以改用html required
属性吗?
这应该是一个评论,但我的声誉不够。