How do I display a new INPUT according to the user's previous answer?

0

I received something off the page:

<INPUT type="radio" name="por_fora" value="SIM">
 <INPUT type="radio" name="por_fora" value="NAO"> 

Depending on the answer, yes or no, I would like to introduce a new question before submit

    
asked by anonymous 17.03.2018 / 13:09

2 answers

1

You'll need JS for this. Leave the question hidden and show it according to the value of the radio field.

  function novaPergunta(value) {
    if(value == 'SIM') {
      document.getElementById('p').style.display = 'block';
    } else {
      document.getElementById('p').style.display = 'none';
    }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Sim<INPUTtype="radio" name="por_fora" value="SIM" onchange="novaPergunta(this.value)">
Nao<INPUT type="radio" name="por_fora" value="NAO" onchange="novaPergunta(this.value)">

<input type="text" name="nova_pergunta" id="p" style="display: none;" />
    
17.03.2018 / 13:48
1

You can use javascript for this .. follow an example.

var form = document.querySelector("#myForm");

form.addEventListener('change', function(ev) {
  let changedElement = ev.target;
  
  if(changedElement.name === 'resp') {
    switch (changedElement.value) {
      case 'SIM':
        addPerguntaExtra();
        break;
      default:
        removePerguntaExtra();
    }
    
  }
  console.log(ev.target);
});

function removePerguntaExtra() {
  let p = document.querySelector('#pergExtra');
  
  if(p) {
    form.removeChild(p);
  }
}


// Também pode usar templates, ou
// a alternativa no html, seta hidden na div, e disabled no input
// e conforme a resposta vc msotra e tira o disabled para o form
// considerar o valor.
function addPerguntaExtra() {
  let perguntaWrapper = createElement('div');
  perguntaWrapper.id = 'pergExtra';
  
  let perguntaLabel = createElement('label', 'Pergunta extra:');
  
  perguntaWrapper.appendChild(perguntaLabel);
  
  let perguntaInput = createElement('input');
  perguntaInput.name = "perguntaExtra";
  perguntaWrapper.appendChild(perguntaInput);
  
  form.appendChild(perguntaWrapper);
}

function createElement(name, content = undefined) {
  let el = document.createElement(name);
  
  if(content) {
    el.textContent = content;
  }
  
  return el;
}
<form id="myForm">
  <label>
  <input type="radio" name="resp" value="SIM">Sim
  </label>
  
  <label>
  <input type="radio" name="resp" value="NAO">Não
  </label>
  
  <!-- Alternativa
    <div id="pergExtra">
      <label>Pergunta extra:</label>
      <input type=text name="perguntaExtra"></input>
    </div>
  -->
</form>
    
17.03.2018 / 13:46