Jack
Jack

Reputation: 683

Changing button value based on toggle

What I want to do is to make the button value to be "1" if the section opened by pressing it is visible, and make it show "2" if the section is not visible. (visible/not visible - hidden/visible).

Here is my failed attempt that I think got the closest to the truth:

    $(document).ready(function(){
    $(".doc1").hide();
    $(".doc").click(function(){
        $(".doc1").slideToggle("fast");

        if($('.doc1').is(':visible')) {
            document.getElementById('doc').value = '1';
        }
        else
            document.getElementById('doc').value = '2';
    });
});

The value is stuck on "2" whether the section is opened (visible) or hidden (.hide).

Upvotes: 0

Views: 151

Answers (4)

Mike Bonds
Mike Bonds

Reputation: 1040

If you are going to use jquery, continue to use it through out. Makes it much easier to go back and fix/read.

Below might be what you are looking for.

$(document).ready(function(){
    $(".doc1").hide();
    $(".doc").click(function(){
        $(".doc1").slideToggle("fast", function() {
           if($(this).is(':visible')) {
              $('#doc').val('1');
           } else {
              $('#doc').val('2');
           }
        });
    });
});

Upvotes: 1

Erik Klop
Erik Klop

Reputation: 135

Not tested, but i would try something like this:

$(document).ready(function(){
    $(".doc1").hide();
    $(".doc").click(function(){
        $(".doc1").slideToggle("fast");

        if($('.doc1').is(':visible')) {

             $(".doc").val("1");  //or .val(1);
        }
        else
             $(".doc").val("2");
    });
});

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

There are a couple things. First you have $(".doc").click. Do you mean $("#doc").click?

Secondly, if you start the animation before you check :visible, it will always be considered visible. You either need to make the value change the callback of the slideToggle call, or just reverse the assignment order and do slideToggle afterwards:

http://jsfiddle.net/95nKw/

Upvotes: 3

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

According to jquery documentation:

During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

May be you should wait until the animation is completed

$(".doc").click(function(){
    $(".doc1").slideToggle("fast", function(){
        if($('.doc1').is(':visible')) {
            document.getElementById('doc').value = '1';
        }
        else
            document.getElementById('doc').value = '2';     
    });
});

Upvotes: 2

Related Questions