is there a better way to check how many inputs have been checked?

1

link

An HTML example:

<div id="1" style="background-color: red;">
    <input type="radio" name="pergunta1">
    <input type="radio" name="pergunta1">
    <input type="radio" name="pergunta1">
    <input type="radio" name="pergunta2">    
</div>

<div id="2">
    <input type="radio" name="pergunta2">
    <input type="radio" name="pergunta2">
    <input type="radio" name="pergunta2">
    <input type="radio" name="pergunta2">    
</div>

<div id="3" style="background-color: red;">
    <input type="radio" name="pergunta3">
    <input type="radio" name="pergunta3">
    <input type="radio" name="pergunta3">
    <input type="radio" name="pergunta3">    
</div>    

<div id="4">
    <input type="radio" name="pergunta4">
    <input type="radio" name="pergunta4">
    <input type="radio" name="pergunta4">
    <input type="radio" name="pergunta4">    
</div>        

<div id="5" style="background-color: blue;">
    <input type="radio" name="pergunta5_5">
    <input type="radio" name="pergunta5_5">
</div>            

<input type="button" value="verificar" id="btn-verifica">

Javascript:

$(document).ready(function(){

    $("#btn-verifica").on("click",function(){
        var contador = 0;
        var totalQuestoes = 5;
        for(var i =0;i<=totalQuestoes; i++){
            if(
                $("[name='pergunta"+(i+1)+"']").is(":checked") ||
                $("[name='pergunta"+(i+1)+"_"+(i+1)+"']").is(":checked")
              ){
                contador++;
            }
        }
        alert(contador);
    });
});
    
asked by anonymous 29.09.2015 / 14:50

1 answer

2

Denali,

You can do this:

$("#btn-verifica").on("click",function(){
    alert($("input[name*='pergunta']:checked").length);
});

Nearly all search loops can be exchanged for jquery selectors, more about it link

    
29.09.2015 / 14:58