9

I am trying to have a section of an html form to show/hide based on a checkbox. This is the essence code I have:

<script src="/js/jquery.js"></script>
<script language="JavaScript">
    function toggle(className){
        var $input = $(this);
        if($(this).prop('checked'))
            $(className).show();
        else
            $(className).hide();
        }
</script>

<fieldset><legend>Check Here
    <input type="checkbox" onclick="toggle('.myClass')" ></legend>
    <span class="myClass">
        <p>This is the text.</p>
    </span>
</fieldset>

When you click on the checkbox, the span gets hidden and will not come back. I have also used $(this).is(':checked'). It appears that $(this).prop('checked') is evaluating to false whether it is checked or not. My best guess is that I am using $(this) incorrectly. What am I missing here?

1

4 Answers 4

22

HTML, pass this from on click event

<input type="checkbox" onclick="toggle('.myClass', this)" ></legend>

JS

function toggle(className, obj) {
    var $input = $(obj);
    if ($input.prop('checked')) $(className).hide();
    else $(className).show();
}

OR, without using prop you can just do:

function toggle(className, obj) {
    if ( obj.checked ) $(className).hide();
    else $(className).show();
}

OR, in one-line using .toggle( display ):

function toggle(className, obj) {
    $(className).toggle( !obj.checked )
}
0
8

Use an event handler that is'nt inline, and then just toggle() the element based on the checkbox state :

<script src="/js/jquery.js"></script>
<script type="text/javaScript">
    $(function() {
        $('input[type="checkbox"]').on('change', function() {
            $(this).closest('fieldset').find('.myClass').toggle(!this.checked);
        });
    });
</script>

<fieldset>
    <legend>Check Here<input type="checkbox"></legend>
    <span class="myClass">
        <p>This is the text.</p>
    </span>
</fieldset>

FIDDLE

This would even work with several fieldset's with the same markup.

1
  • This is probably the 'best' answer in general, but it is a little above my skill level; I try only to use coding that I understand.
    – Andrew
    Apr 2, 2013 at 15:20
7

try binding event via jQuery, and then you can access to $(this):

$(document).ready(function() {
  $(":checkbox").click(function(event) {
    if ($(this).is(":checked"))
      $(".myClass").show();
    else
      $(".myClass").hide();
  });
});
-1
<input type="checkbox" checked>
<input type="text" id="amount">

$document.ready(function() {
 $("input:checked").on("click",function () {
   $("#amount").toggle()
 })
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.