JQuery click event on checkbox not working

I have the following code that I am trying to get. I want the rows of the table with the class generator to be displayed if the checkbox is checked and removed if it is not set (by default). I tested jquery and I know that it loads normally, so this is not a problem.

Below is my code that I was trying to adapt from jQuery flag event handling :

<script> $('#gen_form input:checkbox').click(function() { var $this = $(this); // $this will contain a reference to the checkbox if ($this.is(':checked')) { $(".generator").toggle(); } else { $(".generator").toggle(); } }); </script> <?php if(isset($msg)){ echo "<span id='msg'>".$msg."</span>"; }?> <h2>Add CLLI</h2> <form method="post" id='gen_form'> <table class="form_table_newuser"> <tr> <td class='tdl'>Generator</td><td class='tdr'><input type='checkbox' id='showGen' name='generator' /></td><td>&nbsp;</td> </tr> <tr class='generator'> <td class='tdl'>Start Time</td><td class='tdr'><input type='text' name='start_time' class='textbox'/></td><td>&nbsp;<span class='error'>*<?php echo $errors['start_time']; ?></span></td> </tr> <tr class='generator'> <td class='tdl'>End Time</td><td class='tdr'><input type='text' name='end_time' class='textbox'/></td><td>&nbsp;<span class='error'>*<?php echo $errors['end_time']; ?></span></td> </tr> 

I'm still pretty new to jQuery and am learning. Everything I tried with checking the checkbox failed. I can use the button and it worked (with a different code), but I have to use this checkbox. I tried a few more things before posting them, which say that they all deal with the flag, but none of them did anything at all by clicking the flag.

+4
source share
3 answers

You need to wrap the function in the document callback, otherwise the elements will not exist at the time the handler is bound:

 $(document).ready(function() { $('#gen_form input:checkbox').click(function() { $(".generator").toggle(); // simplifies to this }); }); 

In addition, jQuery .toggle() handles the hide / show alternately for you.

+8
source

Try putting your code inside the $(document).ready handler, according to the structure of your markup, it seems that you just want to select a single input element, try the following:

 $(document).ready(function(){ $('#showGen').change(function(){ $('.generator').css('display', this.checked ? 'block' : 'none'); // or $('.generator').toggle() }) }) 
+2
source

This is because dom is not ready, your script runs before the elements exist.

If you wrap your script in a jQuery document so that it works: -

 $(function(){ $('#gen_form input:checkbox').click(function() { var $this = $(this); // $this will contain a reference to the checkbox if ($this.is(':checked')) { $(".generator").toggle(); } else { $(".generator").toggle(); } }); }); 

I tried it in jsFiddle and it worked

+1
source

All Articles