Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...