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. The intencion is cleaner and generic code in front--end.
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
<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 Attribute can decalared only once
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.