John
John

Reputation: 1629

Variable keeps old value

Whenever i click the '#print' button for the second time, the value from the first click prints out before the real value.

For example: I click button for the first time. The alert box prints out the correct value ('test1').

I click button for the second time. The alert box prints out first value ('test1'), then i press OK, and right after that, the alert box prints out the second value ('test2').

Any ideas what i am doing wrong?

$(".ipdate").focus(function() {

    /*$('.dateBox').hide();*/

    var tit = $(this).attr('id');
    /*var full = '#'+tit+'B';*/

    $('#dateBox').show();

    $('#print').on('click', function(){

       var bottle = $('.sday').val()+' '+$('.smon').val()+' '+$('.syear').val();
       $('#'+tit).val(bottle);
       alert(tit);

    });

    $('#close').on('click',function() {

         $('#dateBox').hide(); 

    });    
});

Upvotes: 1

Views: 1374

Answers (1)

Travis J
Travis J

Reputation: 82267

You are registering multiple events and that is why you see multiple actions! Did you see that? :) I had a similar situation and it took me a while to pick those out. You can unregister for the old event before issuing the new one.

   $(".ipdate").focus(function() {

        /*$('.dateBox').hide();*/

        var tit = $(this).attr('id');
        /*var full = '#'+tit+'B';*/

        $('#dateBox').show();

        $('#print').off('click');
        $('#print').on('click', function(){

            var bottle = $('.sday').val()+' '+$('.smon').val()+' '+$('.syear').val();
            $('#'+tit).val(bottle);
            alert(tit);

        });

        $('#close').off('click');
        $('#close').on('click',function() {

           $('#dateBox').hide(); 

        });



    });

This should fix your issue. Using off will unregister the old events.

Upvotes: 5

Related Questions