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.
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.
Syntax: $(selector).hide(speed,callback); $(selector).show(speed,callback);
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);
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>
Try this
$(".answer").hide(); $(".coupon_question").click(function() { if($(this).is(":checked")) { $(".answer").show(300); } else { $(".answer").hide(200); } });
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With