Question

I want to backup a textbox value in order to allow table filtering. When user press backspace and leave the textbox empty I want to put the previous value I backed up previously:

vbackup stores the initial textbox value, this is "hello" in the jsfiddle.

$('#btn').click(function () {
    $('#mydiv').slideToggle('fast', function () {
        // I SAVE THE TEXTBOX VALUE SO THAT I CAN
        // GET IT BACK AFTERWARDS
        var vbackup = $('#txtbox').val();
        alert(vbackup);
        if ($(this).is(":visible")) {
            // NO MATTERS...
        }
        else {
            // IF TEXTBOX VALUE IS EMPTY I GET THE PREVIOUS
            // VALUE BACK
            if ($('#txtbox').val() == '') {
                // VBACKUP IS EMPTY !!
                alert(vbackup );
                $('#txtbox').val(vbackup );
            }
        }
    });

    return false;
});

I can't understand why my vbackup variable matches with the textbox actual value since I backuped up earlier.

http://jsfiddle.net/QFQ5k/16/

Procedure:

  1. Press the button once
  2. empty the textbox
  3. Press the button again. Now the "hello" word should be get back from the variable to the textbox. The alert tells that the value in my variable has been overriden.
Was it helpful?

Solution

See updated http://jsfiddle.net/QFQ5k/21/

$('#mydiv').hide();
var vbackup = $('#txtbox').val();
$('#btn').click(function () {
        $('#mydiv').slideToggle('fast', function () {

            alert(vbackup);
            if ($(this).is(":visible")) {

            }
            else {
                if ($('#txtbox').val() == '') {
                    // In this alert vbackup
                    // is empty !!
                     $('#txtbox').val(vbackup );

                }
                else 
                    vbackup = $('#txtbox').val();
            }
        });

        return false;
    });

OTHER TIPS

Something like this (storing the value in property of html node) may also be ok. Plus it doesn't make use of global variables (yay).

// this is equal to #mydiv
this.vbackup = $("#txtbox").val()

Checkout the demo here: http://jsfiddle.net/QFQ5k/25/

$("#mydiv").hide();

$('#btn').click(function () {
    $('#mydiv').slideToggle('fast', function () {
        var value = $('#txtbox').val() || $(this).data("value");

        if ( !$(this).is(":visible") && !$('#txtbox').val() ) {
            $('#txtbox').val( value );
        }

        $(this).data("value", value);
    });

    return false;
});

http://jsfiddle.net/QFQ5k/26/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top