开发者

jQuery + Multiple Checkboxes: Show div on checked, Hide on uncheck

I got multiple checkboxes generated from a PHP script.

<input type="checkbox" class="checkbox" name="item[]" value="1" />

<input type="checkbox" class="checkbox" name="item[]" value="2" />

<input type="checkb开发者_StackOverflowox" class="checkbox" name="item[]" value="3" />

<input type="checkbox" class="checkbox" name="item[]" value="4" />

Now, once a checkbox gets checked - I want to show a div with options like "Delete Selected". But, after all checkboxes are unchecked, the DIV should disappear again. I have got the following code, but it does not hide the DIV.

    $(".checkbox").live('click', function () {

        countChecked () ;

        if (countChecked() == "1" ) {

            $("div#options").fadeOut("medium") ;

        } else {

            if ( $("div#options").is(":hidden") ) {

                $("div#options").fadeIn ( "medium" ) ;

            }

        }

    });

Also, the "countChecked"-function is shown below.

    function countChecked() {

        var n = $("input.checkbox:checked").length;

    }


Your function should return the value:

function countChecked() {
    return $("input.checkbox:checked").length;
}

And you want to check if the amount is 0, also you can remove the duplicate call to countChecked

$(".checkbox").live('click', function () {
    if (countChecked() == 0 ) {


in your countChecked()-function, use return statement..

 function countChecked() {

        var n = $("input.checkbox:checked").length;
        return n;

    }

and while clicking on checkboxes...

 $(".checkbox").live('click', function () {

        if (countChecked() == 0 ) {

            $("div#options").fadeOut("medium") ;

        } else {

            if ( $("div#options").is(":hidden") ) {

                $("div#options").fadeIn ( "medium" ) ;

            }

        }

    });


You can use

$('.checkbox').live('click',function(){
    // if you just checked the current one, no need to check the rest
    if (this.checked)
    {
      $('#options').fadeIn('medium');
    }
    else // if you just unchecked
    {
        if ( !$('.checkbox:checked').length ) // check the whole group
        {
            $('#options').fadeOut('medium');
        }
    }
});

demo at http://jsfiddle.net/gaby/wZWbS/


Working: http://jsfiddle.net/NkkJF/


Another version, with tiny optimalization: http://jsfiddle.net/Briganti/XNWEP/

Have fun :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜