Get the most selected radio input with Javascript

Asked

Viewed 335 times

3

I’m putting together a test, I just have the html structure done, I wanted to know how to know which of the radio input is most selected. Ex.: Most selected was "A)" then when submitting the form, is displaying the image corresponding to most letter "A)" and so on with the other alternatives "B)", "C"), "D)" E "E)"... 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>

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: http://jsfiddle.net/yLgrtaw3/

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

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

  • 1

    Also for more organized HTML: http://jsfiddle.net/yLgrtaw3/2/

  • Thank you very much, this will help me a lot! But how do I stop instead of appearing the number of selected alternatives, appear the result corresponding to most selected alternatives... I could even direct to an html page where I will create one for each letter... If the majority is "a" javascript directs to an html page referring to most of "a" there will be an image and a few more things I want to add... Why so, I wanted to take a personality test...

  • @Karina is what you’re looking for: http://jsfiddle.net/m3toobdk/1/ ?

  • 1

    Perfect, just that!!! Thank you very much, from my heart.

  • @Karina.

Browser other questions tagged

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