user3230425
user3230425

Reputation: 695

How to store value of a textbox without losing focus?

I am trying to store value in a textbox. It works fine if I enter a value in the text box and then click outside the textbox and refresh it. I want to know if it is possible to just enter a value in the textbox and directly refresh the page without clicking outside the textbox?

Here is the script:

 <script>
 jQuery(function ($) {
   if (typeof (window.localStorage) != "undefined") {
    //set the value to the text fields
    $("input[type=text]").val(function () {
        return localStorage.getItem(this.id);
    });

    $("input[type=text]").on("change", function () {
        localStorage.setItem(this.id, $(this).val());
    });
     }
 });
</script>

FIDDLE

Upvotes: 2

Views: 840

Answers (3)

kiprainey
kiprainey

Reputation: 3291

An easy way to do this would be to listen for a keyup event within the form field rather than the change event.

$("input[type=text]").on("keyup", function () {
    localStorage.setItem(this.id, $(this).val());
});

Here's an updated fiddle that demonstrates how this would work. http://jsfiddle.net/hb8eW/16/

... and here's a quick fiddle that demonstrates the difference between jQuery's keypress, keyup, and change events. Note when content is updated after different events (and that keypress is always one character behind). http://jsfiddle.net/krainey/UhR85/

You can read about keyup here: http://api.jquery.com/keyup/

Upvotes: 2

Venkata Krishna
Venkata Krishna

Reputation: 15112

http://jsfiddle.net/hb8eW/15/

Use keyup event instead of change event.

$("input[type=text]").on("keyup", function () {
    localStorage.setItem(this.id, $(this).val());
});

Upvotes: 2

Joel
Joel

Reputation: 2257

The change event is only triggered when the textbox loses focus. You can use the keyup event instead to refresh immediately.

Upvotes: 0

Related Questions