How do I display a new INPUT as per the user’s previous response?

Asked

Viewed 41 times

0

Getting something off the sheet:

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

According to the answer, yes or no, I would like to ask a new question before the submit

2 answers

1

You can use javascript for this.. Here’s 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>

0


You’re gonna need JS for this. Leave the questions hidden and show it according to the value of the field radio.

  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<INPUT type="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;" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.