How to check with jQuery if there is a checkbox checked?

Asked

Viewed 95,476 times

29

I would like to know which Checkbox is checked with Jquery.

To catch all the checks I made the following code

var checado=false;
$(obj).find("input[name='analisar']").each(function(){
    if($(this).attr("checked")=="checked")
       checado=true;
});
if(!checado){
     alert("Deve ser selecionado uma opção entre Aprovado/Desaprovado!");
     return false;
}else....

But it is returning whenever none is selected. How do I see if at least one is selected.

Example: http://jsfiddle.net/lionbtt/AGbCY/

  • 1

    If you can also provide HTML or direct a jsfiddle with your attempt it makes it easier to give an answer

8 answers

25


Use the method prop instead of attr.

Elaborating the answer: there is a certain difference between attributes and properties of HTML elements. I leave it to you to study this difference ;) checked is not an attribute, but a property. The method prop, according to the link I mentioned, it was inserted in jQuery version 1.6 to handle it.

  • 1

    Thanks man, that’s right.

22

jQuery has a shortcut to this, the pseudo-class :checked (that is part of CSS3). With this you can reduce your code well:

var checado = $(obj).find("input[name='analisar']:checked").length > 0;
  • If I have more than two checked, as is the variable checado? I mean, she’ll be one object or he will return boolean?. Thanks.

  • I forgot to add the check at the end of the line. See if the length of the returned jQuery object is greater than 0, then you guarantee a boolean.

  • 1

    Good guy, it’ll help a lot.

18

12

if( $("#id_element").is(":checked") == true/false )
  • 2

    You can add text explaining your answer?

  • I found it easy and it helped me

4

To check if there is one selected, you can use the $(':radio').is(':checked');

Follow a simple example; =D

var ok = "#btnOK";
var clean = "#btnClean";
var radio = ":radio";
var msgbox ="#msg-box span";
var color;

$(ok).on("click" , function(){
  //Check se há alguma opção selecionada
  if($(radio).is(":checked")){

    $.each($("input[type='radio']"), function(id , val){
      if($(val).is(":checked")){
        color = $(val).val();
        return false;
      };
    });
    //var color = $(radio).is("checked").prop("id");
    console.log(color);
    $(msgbox)
    .html("Foi selecionado a opção <strong>" + color + "</strong>.")
    .removeClass()
    .addClass("alert alert-success")
    .show();

    setTimeout(function(){
      $(msgbox).hide();
    } , 5000);                      
  } else {

    $(msgbox)
    .html("Não foi selecionado nenhuma opção")
    .removeClass()
    .addClass("alert alert-danger")
    .show();

    setTimeout(function(){
      $(msgbox + " span").hide();
    } , 5000);

  }
});

$(clean).on('click' , function(){
  $(radio).prop("checked" , false); 
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<div class="container">
            <div id="msg-box">
                <span></span>
            </div>
            <h1>Selecio sua cor favorita</h1>
            <div class="radio">
                <label>
                    <input type="radio" name="optionsColors" id="optYellow" value="amarelo" > Amarelo
                </label>
            </div>
            <div class="radio">
                <label>
                    <input type="radio" name="optionsColors" id="optBlue" value="azul" > Azul
                </label>
            </div>
            <div class="radio">
                <label>
                    <input type="radio" name="optionsColors" id="optWhite" value="branco" > Branco
                </label>
            </div>
            <div class="radio">
                 <label>
                    <input type="radio" name="optionsColors" id="optBlack" value="preto" > Preto
                </label>
            </div>
            <div class="radio">
                <label>
                    <input type="radio" name="optionsColors" id="optRed" value="vermelho" > Vermelho
                </label>
            </div>
            <div class="radio">
                <label>
                    <input type="radio" name="optionsColors" id="optGreen" value="verde" > Verde
                </label>
            </div>
            
            <div>
                <button type="button" class="btn btn-primary" id="btnOK">
                    <span>OK</span>
                </button>
                <button type="button" class="btn btn-danger" id="btnClean">
                    <span>Limpar</span>
                </button>
            </div>
        </div>

4

From jQuery 1.6, the method .prop() provides a way to explicitly retrieve property values, while .attr() recovers attributes.

they checked. true(Boolean): Will change checkbox status
$( elem ).prop( "checked" ) true(Boolean): Will change checkbox status
elem.getattribute( "checked" ) "checked"(String): Initial checkbox status; Does not change
$( elem ).attr( "checked" ) (1.6) "checked"(String): Initial checkbox status; Does not change
$( elem ).attr( "checked" ) (1.6.1+) "checked"(String): Will change checkbox status
$( elem ).attr( "checked" ) (pre-1.6) "checked"(String): Change with checkbox status

var checado=false;
$(obj).find("input[name='analisar']").each(function(){
    if($(this).prop("checked"))
        checado=true;
});
if(!checado){
    alert("Deve ser selecionado uma opção entre Aprovado/Desaprovado!");
    return false;
}else....

Source: http://api.jquery.com/prop/

  • It would be helpful if you could add a little explanation.

3

function validaTermo() {

    var checado = $("#termo").is(':checked')
    if(checado == true){
        //checado
    }

    console.log(checado);
}
  • How his response differs from the existing ?

1

The question is about jQuery, but I believe it fits an alternative with pure Javascript:

const checkbox = document.querySelector("#checkbox");

if(checkbox.checked === true) {
    console.log("Está checada!");
}

We simply select the element and then check the checked value, if true the checkbox is checked.

I believe that this alternative is even simpler than with jQuery, because the property checked is easily accessible.

We can insert into a conditional, test its value and proceed with logic.

Browser other questions tagged

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