Baylock
Baylock

Reputation: 1260

jquery event only if condition met

This is my script:

<script>

if( $('.mydiv').css('display') == 'block'){
    $(".input_a").keyup(function(){
        $(".input_b").val( this.value );
    }); 
};

$('.mybutton').toggle(
    function(){
        $('.mydiv').css('display','none');
        $(".input_b").val('');
        // now, the event inside the "IF" here above should not occur but it does...
    },
    function(){
        $('.mydiv').css('display','block');
        var f1 = $(".input_a").val();
        $(".input_b").val(f1);
    }        
);

</script>

What I'm tring to do:

I have to input fields and a div displayed.

This is what my script is about, but the "IF" doesn't seem to work as when the div is hidden, filling in the input B is still mirrored on the input B.

Where am I wrong?

Thank you for your help.

Upvotes: 0

Views: 2635

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388446

Try

jQuery(function ($) {
    //cache variables
    var $ina = $(".input_a"),
        $inb = $(".input_b"),
        $div = $('.mydiv');
    $ina.keyup(function () {
        //check the condition within the keyup handler
        if ($div.is(':visible')) {
            $inb.val(this.value);
        };
    });

    $('.mybutton').toggle(function () {
        $div.hide();
        $inb.val('');
    }, function () {
        $div.show();
        $inb.val($ina.val());
    });
})

Demo: Fiddle

Upvotes: 1

Dat Nguyen
Dat Nguyen

Reputation: 1891

You can do it very simple:

<script>
    $(".input_a").keyup(function(){
        if($('.mydiv').is(':visible')){
            $(".input_b").val($(this).val());
        }else {
            $(".input_b").val('');
        }
    }); 
</script>

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use :visible-selector like,

if( $('.mydiv:visible').length){
    $(".input_a").keyup(function(){
        $(".input_b").val( this.value );
    }); 
};

Or you can use is() like

if( $('.mydiv').is(':visible')){
   ...
}

Use $('.mydiv').hide(); in place of $('.mydiv').css('display','none');

And use $('.mydiv').show(); in place of $('.mydiv').css('display','block');

Read hide() and show()

Try the Full code

$(function(){
    if( $('.mydiv').is(':visible')) {// use is and :visible selector
        $(".input_a").keyup(function(){
            $(".input_b").val( this.value );
        }); 
    };

    $('.mybutton').toggle(function(){
            $('.mydiv').hide(); // use hide()
            $(".input_a").off('keyup');// off/remove the keyup event
            $(".input_b").val('');
        }, function(){
            $('.mydiv').show();// use show()
            var f1 = $(".input_a").val();
            $(".input_b").val(f1);
        }        
    );
});

Upvotes: 1

Prashobh
Prashobh

Reputation: 9544

You can try with .is(':visible')

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

}

Upvotes: 1

Related Questions