0

I'm working on a project where I have a checkbox and I want a function to run when the checkbox changes form ticked to unticked or vice versa.

Here is the checkbox:

<input class="form-control main_checkbox_class"
       type="checkbox"
       value="1"
       checked="checked"
       id="main_checkbox_id" >

And then in my javascript I have:

jQuery(function($) {
  $('.main_checkbox_class').change(console.log('hello'));
});

However when I run this, on page load 'hello' is printed to the console and then nothing happens when I check or uncheck the check box, I'm not sure why this is happening and any help fixing this would be greatly appreciated.

user2320239
  • 1,021
  • 2
  • 18
  • 43

2 Answers2

2
$(function() {
  $('.main_checkbox_class').change(function() {
    console.log( $(this).is(':checked') );
  });
});
Alex
  • 9,911
  • 5
  • 33
  • 52
2

You need to provide the event handler as a function reference. At the moment your code is running on load as you're assigning the result of console.log to the event handler. Try this:

$('.main_checkbox_class').change(function() {
  console.log('hello');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you this is the answer, I'm pretty new to javascript and I keep getting tripped up by this. I'll accept after 10 mins. – user2320239 Oct 06 '16 at 08:27