Get the most selected radio input with JavaScript

3

I'm setting up a test, I'm just having the html structure done, I wanted to know how to do which input radio is most selected. Ex: The most selected was "A", so when sending the form, the image corresponding to most letters "A" and so on with the other alternatives "B", "C"), "D" " AND IS)"...  is a very simple html ...

1) Questão 1
</font><font size=4 color="black" face="arial"><p>
<label>
<input type="radio" name="questao1" value="a" /> A) resoposta 1 </label>
<br />
<label>
<input type="radio" name="questao1" value="b" /> B) resposta 2</label>
<br />
<label>
<input type="radio" name="questao1" value="c" /> C) resposta 3</label>
<br />
<label>
<input type="radio" name="questao1" value="d" /> D) resposta 4</label>
<br>
2) Questão 2
</font><font size=4 color="black" face="arial"><p>
<label>
<input type="radio" name="questao2" value="a" /> A) resoposta 1 </label>
<br />
<label>
<input type="radio" name="questao2" value="b" /> B) resposta 2</label>
<br />
<label>
<input type="radio" name="questao2" value="c" /> C) resposta 3</label>
<br />
<label>
<input type="radio" name="questao2" value="d" /> D) resposta 4</label>
    
asked by anonymous 12.09.2015 / 15:20

1 answer

6

You can do it this way:

var inputs = document.querySelectorAll('input');
var button = document.querySelector('button');
button.addEventListener('click', verificar);

function verificar() {
    var resultados = {};
    [].forEach.call(inputs, function (input) {
        var letra = input.value;
        if (!resultados[letra]) resultados[letra] = 0;
        if (input.checked) resultados[letra]++;
    });
    alert(JSON.stringify(resultados, null, 4));
}

jsFiddle: link

I've added a button to your HTML to start the scan. So when the button is clicked, it is called the verificar function that traverses all inputs and is filling the resultados object. Each time you find one that is checked (ie: input.checked ) then it adds one more.

At the end I gave an alert, but you could also do return in the function and use any other logic you have.

    
12.09.2015 / 15:39