How to check if a checkbox is checked with jquery? [duplicate]

2

Hello, I'm trying to do an operation on JS if a checkbox is checked, but I'm not getting success. Here is the code:

  $('#btn-proximo').click(function(e){
            if($('#in_acesso').is('checked')){

            $('#div_valida :input').each(function(){
              if(this.value == "" || this.value == " "){
                e.preventDefault();
                 this.focus();

            } 
          if($('#password').val() != $('#password_confirmation').val()){
            $('#dados_gerais').preventDefault();
            $('#erroSenha').show('fade');
            setTimeout(function(){
              $('#erroSenha').hide('fade');
            },6000);
            $('#password').focus();

          }

        })
        }
        })
    
asked by anonymous 05.10.2018 / 17:13

2 answers

3

JQUERY - CHECKING A CHECKBOX WITH IS (': CHECKED')

The first way to do this is to use jQuery's is () function. It checks whether the argument, or set of arguments you have declared satisfies the given condition. If so, it returns "true." If it does not, it returns "false."

To use is (), we first need to choose the element and then do the check using the :checked selector, which works with checkboxes, among others.

You simply used checked without : (colon)

See

$('#btn-proximo').click(function(e){
     if($('#in_acesso').is('checked')){
          console.log("primeiro codigo");   
     }

     if($('#in_acesso').is(':checked')){
          console.log("segundo codigo");
     }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btn-proximo">proximo</button>

<input type="checkbox" id="in_acesso">
    
05.10.2018 / 19:26
3

Jquery has the :checked selector, and with the help of length you can get a value of 1 when the object is selected. This way, you can "check" one or more checkboxes. While the checkbox is not selected, it has a value of 0, so you can develop your logic from this functionality. I hope it helps. Here is the sample code:

$('#check').on('click', function(){
 var checkbox = $('#check:checked').length;
  console.log(checkbox);
  
  if(checkbox === 1)
  {
    alert('Parabéns! \o/');
  }
});
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><body><inputtype="checkbox" id="check">
  </body>
</html>
    
05.10.2018 / 22:23