How to check if a checkbox is checked with jquery?

Asked

Viewed 3,463 times

2

Hello, I’m trying to do a JS operation if a checkbox is checked, but I’m not succeeding. Follow 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();

          }

        })
        }
        })
  • 3

    Put the : before checked, so .is(':checked')

  • change the line if($('#in_access').is('checked')){ to if($('#in_access').is(':checked'){ Only ":" was missing before "checked"

2 answers

4


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

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

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

You just used checked without : (colon)

Behold

$('#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>


<button id="btn-proximo">proximo</button>

<input type="checkbox" id="in_acesso">

3

Jquery has the selector :checked, and with the help of length you can get the value 1 when the object is selected. This way, you can "check" one or more checkbox. While the checkbox is not selected, it has value 0, so you can develop your logic from this feature. I hope it helps. Follow the example 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>
    <input type="checkbox" id="check">
  </body>
</html>

Browser other questions tagged

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