-1

I have an input like

   <input  type="checkbox" name="acept" id="acept">

and some simple JS/jquery code like

$('#acept').click(function(){

    /* if( $("#acept").checked ){
        alert(" I'm checked ");
    } */

    if( this.checked ){
        alert(" I'm checked ");
    }

})

Now, the first 'if' (the commented one) doesn't work, but the second one does. Any explanation as to why?

Let
  • 60
  • 8

1 Answers1

3

That is because $("#acept") is a jQuery object and does not have any property checked on that directly, you can either use index or do that using jQuery's builtin methods like .prop('checked') or .is(':checked'):

$('#acept').click(function(){
  console.log($("#acept").checked); //undefined
  if( $("#acept").is(':checked') ){
    alert(" I'm checked ");
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  type="checkbox" name="acept" id="acept">
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 2
    I think in this case OP just wants to know why the first doesn't work; in all practicality, using `this.checked` would be better imo. – Ja͢ck Mar 04 '20 at 16:48