Make field required depending on the answer

1

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?

    
asked by anonymous 01.02.2017 / 16:51

3 answers

4

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>
    
01.02.2017 / 17:06
1
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);
}
    
01.02.2017 / 16:56
1

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.

    
01.02.2017 / 17:06