I have a medical form, and the following change was requested:
If field 1 is checked = 1, make field 2 mandatory. If not checked do not make it as mandatory.
Could anyone help me?
I have a medical form, and the following change was requested:
If field 1 is checked = 1, make field 2 mandatory. If not checked do not make it as mandatory.
Could anyone help me?
You can do this:
const camp1 = document.getElementById('campo1');
const camp2 = document.getElementById('campo2');
const btn_sub = document.getElementById('btn-submit');
btn_sub.addEventListener('click', function() {
if(camp1.checked && !camp2.checked) {
alert('Campo 2 obrigatório');
return;
}
alert('É Válido')
});
<input id="campo1" type="checkbox">1
<br>
<input id="campo2" type="checkbox">2
<button id="btn-submit">Enviar</button>
var camp1 = $('campo1'); var camp2 = $('campo1'); if(camp1.val() == 1){ camp2.attr('required', true); }
You can use getElementById
var camp1 = getElementById('#camp1'); var camp2 = getElementById('#camp2'); if(camp1.val() == 1){ camp2.attr('required', true); }
The following example uses JavaScript
, Jquery
, and the required
function in HTML5.
$('.pergunta').change(function() {
var chars = parseInt(this.value);
if (chars === 1) {
$('#retorno').html('<input type="checkbox" name="campo2" required=""> Obrigatório');
return;
} else {
$('#retorno').html('<input type="checkbox" name="campo2"> Não Obrigatório');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" class="pergunta" name="checado" value="1" required>Sim
<input type="checkbox" class="pergunta" name="checado" value="2" required>Não
<div id="retorno"></div>
I hope to help.