Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Tags:

jquery

I have this code:

   <fieldset class="question">        <label for="coupon_question">Do you have a coupon?</label>        <input class="coupon_question" type="checkbox" name="coupon_question" value="1" />        <span class="item-text">Yes</span>    </fieldset>     <fieldset class="answer">        <label for="coupon_field">Your coupon:</label>        <input type="text" name="coupon_field" id="coupon_field"/>    </fieldset> 

And I would like to show/hide the "answer" fieldset (default is hidden) after a click on the checkbox in fieldset "question" How to do that. I wasn't able to do that using the technique for a classic elemetn like:

<script>     $().ready(function(){          $('.question').live('click',function() {                  $('.answer').show(300);             }             ,             function(){                 $('.answer').hide(200);             }         );      }); </script> 

Could somebody help me how to do that using checkbox? Also if possible to null (uncheck) the checkbox when it's hidden.

like image 431
dmn77 Avatar asked Aug 19 '13 06:08

dmn77


People also ask

How do you show and hide div elements based on the click of checkboxes in jQuery?

In order to display data/content of a specific element by selecting the particular checkbox in jQuery we can use the toggle() method. The toggle() method is used to check the visibility of selected elements to toggle between hide() and show() for the selected elements.

How do you do show hide in jQuery?

Syntax: $(selector).hide(speed,callback); $(selector).show(speed,callback);

How do you check checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


Video Answer


2 Answers

Attach onchange event to the checkbox:

<input class="coupon_question" type="checkbox" name="coupon_question" value="1" onchange="valueChanged()"/>  <script type="text/javascript">     function valueChanged()     {         if($('.coupon_question').is(":checked"))                $(".answer").show();         else             $(".answer").hide();     } </script> 
like image 62
abhinsit Avatar answered Sep 17 '22 14:09

abhinsit


Try this

$(".answer").hide(); $(".coupon_question").click(function() {     if($(this).is(":checked")) {         $(".answer").show(300);     } else {         $(".answer").hide(200);     } }); 

FIDDLE

like image 33
Eswara Reddy Avatar answered Sep 20 '22 14:09

Eswara Reddy