dmn77 dmn77 - 9 days ago 5
jQuery Question

How to show/hide an element on checkbox checked/unchecked states using 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.

Answer

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>