[英]Radio/Toogle Button with validation in the form
I'm creating a simple form with radio button group field and selection use toggle button. 我正在使用单选按钮组字段和选择使用切换按钮创建一个简单的表单。 Validation work normally, except this one.
除此一项外,验证工作正常。
Use the PHP/Laravel language, but would like to solve with JS (Vanilla), if possible. 使用PHP / Laravel语言,但如果可能的话,希望使用JS(Vanilla)解决。 The intencion is cleaner and generic code in front--end.
这样做的目的是在前端使用更干净,更通用的代码。
HTML 的HTML
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label>Documento</label>
<div data-toggle="buttons">
<div class="btn-group">
<label class="btn btn-info btn-lg">
<input type="radio" name="type" value="CNH" class="sr-only" required>
CNH
</label>
<label class="btn btn-info btn-lg" style="margin-left: 5px;">
<input type="radio" name="type" value="CPF" class="sr-only" required>
CPF
</label>
<label class="btn btn-info btn-lg" style="margin-left: 5px;">
<input type="radio" name="type" value="ID" class="sr-only" required>
Identidade (R.G.)
</label>
</div>
</div>
<div class="invalid-feedback">Selecione o documento que será utilizado.</div>
</div>
<div class="col-md-4 mb-3">
<label for="numberDocument">Número</label>
<input type="text" class="form-control" id="numberDocument" required>
<div class="invalid-feedback">
Número não informado!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="clientName">Nome</label>
<input type="text" class="form-control" id="clientName" required>
<div class="invalid-feedback">
Nome do cliente não informado!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
JS JS
<script type="text/javascript">
(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);
})();
First of all, 首先,
<input type="radio" name="type" id="document" value="CNH" class="sr-only" required>
id="document" used in three times id =“ document”使用了三遍
Id Attribute can decalared only once ID属性只能声明一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.