Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide with Checkbox using jQuery

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?

like image 480
Andrew Avatar asked Apr 02 '13 14:04

Andrew


People also ask

How to hide check box in jQuery?

< script type = "text/javascript" > $(document). ready(function() { $('#lblForshow'). hide();

How to show and hide div element based on the click of checkbox in jQuery?

Answer: Use the jQuery toggle() method The following example will demonstrate you how to show and hide div elements based on the selection of checkboxes using the jQuery toggle() method. The div boxes in the example are hidden by default using the CSS display property which value is set to none .

How to hide checkbox in javascript?

The checkbox of the any list item can be hidden by using htmlAttributes of fields object. With the help of htmlAttributes we can add unique class to each list item that will be rendered from the data source, from the CSS class we can hide the checkbox of the list item.


1 Answers

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 )
}
like image 98
palaѕн Avatar answered Oct 07 '22 18:10

palaѕн