Is there a better way to check how many inputs were checked?

Asked

Viewed 22 times

1

http://jsfiddle.net/3q4h6tnL/

An example in HTML:

<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);
    });
});

1 answer

2


Denali,

You can do it like this:

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

Virtually all search loops can be replaced by jquery selectors, more about this https://api.jquery.com/category/selectors/

  • Wow, a lot easier

  • good that helped you @Denali another tip, virtually all jquery selectors can be combined to go refining the search more and more.

Browser other questions tagged

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