There are a few ways to do this. As a beginner, I'll put the "simplest" (I found) way to do this, but not the best.
First, let's look at a working example:
<script>
function PreencherCampo(){
var pergunta1 = document.getElementById("pergunta1").innerHTML;
var pergunta2 = document.getElementById("pergunta2").innerHTML;
var elementos1 = document.getElementsByName('pergunta1');
var resposta1 = '';
for (i = 0; i < elementos1.length; i++) {
if (elementos1[i].checked) {
resposta1 = elementos1[i].value;
}
}
var elementos2 = document.getElementsByName('pergunta2');
var resposta2 = '';
for (i = 0; i < elementos2.length; i++) {
if (elementos2[i].checked) {
resposta2 = elementos2[i].value;
}
}
document.getElementById("resposta").innerHTML = pergunta1 + ': ' + resposta1 + '\n'+
pergunta2 + ': ' + resposta2;
}
</script>
<p id="pergunta1">Pergunta1?</p>
<input type="radio"name="pergunta1"value="Sim" checked/>SIM
<input type="radio"name="pergunta1"value="Não"/>Não
<p id="pergunta2">Pergunta2?</p>
<input type="radio"name="pergunta2"value="Sim" checked/>SIM
<input type="radio"name="pergunta2"value="Não"/>Não
<br>
<p>
<input type="submit"value="Enviar" onclick="PreencherCampo()"/>
</p>
<br>
<p>
<textarea name"mensagem" rows="10" cols="27" id="resposta"></textarea>
</p>
In this example, we first get the value of each question by id
of elements, like this:
var pergunta1 = document.getElementById("pergunta1").innerHTML;
var pergunta2 = document.getElementById("pergunta2").innerHTML;
After this, we will get all radios
by name
, and after that check what is with the checked
attribute (which indicates which is checked or not).
var elementos1 = document.getElementsByName('pergunta1');
var resposta1 = '';
for (i = 0; i < elementos1.length; i++) {
if (elementos1[i].checked) {
resposta1 = elementos1[i].value;
}
}
And we do the same thing with the second group, as the example code shows. If we had more, we would create the third and so on.
After this, we need to put the value in textarea
, and for this we just get the element (textarea) by id
and set innerHTML
to the value we want, like this:
document.getElementById("resposta").innerHTML = pergunta1 + ': ' + resposta1 + '\n'+
pergunta2 + ': ' + resposta2;
Finally, we'll call our function by clicking the submit button, by event .onclick () on our button, like this:
<input type="submit"value="Enviar" onclick="PreencherCampo()"/>
With all this, we have the expected result, using only javascript .