Show/Hide with Checkbox using jQuery

让人想犯罪 __ 提交于 2019-11-29 02:17:13

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 )
}

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.

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();
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!