MMK
MMK

Reputation: 605

Why does none of click or change event trigger my function?

Well i checked the jQuery documentation and according to it i can do something like:

function notifyme(){
    console.log(true)
}
$('button').on('click', notifyme );

Which is correct. But my code doesn't seem to work.

Here's what i have in my code. I have a div with an id myinput like so:

<div id="myinput">
    <input type="checkbox" value="0"/>
</div>

And this is my jQuery code:

$('#myinput input').on( 
    'change', 
    My_fn( $(this).prop('checked') )
);

My_fn( theVal ){
    if( theVal == true ){
        console.log(true)
    }
    else{
        console.log(false)
    }
}

Even when i try:

$('#myinput input').on( 
    'click', 
    My_fn( $(this).prop('checked') )
);

I get no console log.

Interestingly if i place this code at the beginning of the script:

My_fn( $('#myinput input').prop('checked') )

I get a console log of true since the checkbox is checked.

Why does none of click or change event trigger the My_fn() function ?

Answer I got it.

Firstly i removed the parameter for the function when using on. So this My_fn( $(this).prop('checked') ) becomes this My_fn(). Now when using .on(). I simply wrote

$('#myinput input').on( 
    'click', 
    My_fn
);

And it worked. Thanks to anyone who helped.

Upvotes: 0

Views: 59

Answers (2)

Nishit Maheta
Nishit Maheta

Reputation: 6031

try below code . it is wrong to pass $(this).prop('checked') as param in function.

$('#myinput input').on( 
    'click', 
    My_fn
);

My_fn(){
  if( $(this).prop('checked')== true ){
    console.log(true)
  }
  else{
    console.log(false)
  }
}

or you can use is() selector to check weather check box is checked or not

My_fn(){
  if( $(this).is(':checked') == true ){
    console.log(true)
  }
  else{
    console.log(false)
  }
}

Upvotes: 2

Dhiraj
Dhiraj

Reputation: 33618

Declare the function first. When you do a .on() you are already sending a reference of the input element to the event handler (My_fn) so effectively you don't have to send a parameter to the function. Instead in the function handler try to get the properties of the element.

Try something like this

function My_fn(theVal){
  if( $(this).is(':checked') === true ){
    console.log(true)
  }else{
    console.log(false)
  }
}
$('#myinput input').on('change', My_fn);

Upvotes: 1

Related Questions