How to create a function to clean the group of a radiobutton?

2

I'm working on a typing system for a paper form, where I have some radiobutton options, for example:

<fieldset>
   <legend> Disponibilidade de energia elétrica? </legend>
   <label for="sim"> <input type="radio" name="energia" value="sim">Sim</label>
   <label for="nao"> <input type="radio" name="energia" value="nao">Não</label>
</fieldset>

The case is that, eventually, a typist accidentally clicks on a radio to answer a question on the form, however, the question is blank on paper, and undoing the selection.

The default radiobutton group behavior is to allow you to change between options and not to deselect the field.

It also could not be a Clean Form function, as the typist would have to re-type all other fields.

Any ideas? Has anyone had the same problem? How to give a reset in the group "energy", for example?

    
asked by anonymous 20.06.2015 / 20:44

2 answers

1

I believe you just want to clear the selection of a single question, so I created a method by passing the parameter of what question it is and then concatenate to search only the radio belonging to that question.

Example: Question 1 - > radios resposta1

function limparSelecao(questao) {
  var radios = document.querySelectorAll("input[name=resposta" + questao + "]");
  for (var i = 0; i < radios.length; i++)
    radios[i].checked = false;
}

function limparTudo() {
  var radios = document.querySelectorAll("input[name^=resposta]");
  for (var i = 0; i < radios.length; i++)
    radios[i].checked = false;
}
<p>Questão 1</p>
<input type="radio" name="resposta1" value="1" /> Resposta 1 <br/>
<input type="radio" name="resposta1" value="2" /> Resposta 2 <br/>
<input type="radio" name="resposta1" value="3" /> Resposta 3 <br/>
<input type="radio" name="resposta1" value="4" /> Resposta 4 <br/>
<input type="button" value="Limpar" onclick="limparSelecao(1)" />

<p>Questão 2</p>
<input type="radio" name="resposta2" value="1" /> Resposta 1 <br/>
<input type="radio" name="resposta2" value="2" /> Resposta 2 <br/>
<input type="radio" name="resposta2" value="3" /> Resposta 3 <br/>
<input type="radio" name="resposta2" value="4" /> Resposta 4 <br/>
<p><input type="button" value="Limpar" onclick="limparSelecao(2)" /></p>

<p><input type="button" value="Limpar Tudo" onclick="limparTudo()" /></p>
    
20.06.2015 / 21:08
1

You can retrieve the elements of this group by the name attribute using document#getElementsByName() :

function limparPeloNome(nome) {
  var radios = document.getElementsByName(nome);
  for (var i = 0; i < radios.length; i++)
    radios[i].checked = false;
}

document.getElementById('bt-letra').addEventListener('click', function() {
  limparPeloNome('letras');
});
<input type='radio' name='letras' />A
<input type='radio' name='letras' />B
<input type='radio' name='letras' />C
<button id='bt-letra'>Limpar seleção</button>
    
20.06.2015 / 21:12