Goro
Goro

Reputation: 10249

Automatically save textbox contents

I have a textbox that a user can type some text into. The area that the textbox is in can get re-loaded with different HTML depending on what the user does, and I want the textbox to "remember" what the user typed into it when he comes back.

The problem starts with the fact that there are many different ways that the user can navigate away from the textbox - he can load many different HTML segments into my operational area, each erasing the textbox.

Is there a way for me to universally save textbox contents when it is getting unloaded? Is there an equivalent of onUnload() event for textbox?

There are two ways I can see that would solve my problem:

  1. Setup textbox watchdog functions that update text stored in memory whenever user types anything.
  2. Add a saveText() call to every function that reloads the operational area.

Neither of these is particularily appealing. Is there a more elegant way of doing this?

Thanks,

Upvotes: 1

Views: 2654

Answers (1)

Rob W
Rob W

Reputation: 349232

The onchange is what you're looking for. When the user exits the textbox, the change event is fired.

onchange is a better choice than onblur or focusout, because blur and focusout also fire when the contents of the text field hasn't changed.

A basic example:

var textarea = document.getElementById("myTextfield");
textarea.onchange = function(ev){
    call_function_that_saves(this.value);
}

An unload event for non-embedded elements doesn't exist. Consider what would happend when such an event handler exists, and a huge page unloads..

Upvotes: 2

Related Questions