Sergey Scopin
Sergey Scopin

Reputation: 2245

Save value from text area in cookie and then reload page

I have some text area and a table which I want to change after key pressed in text area.

$("#fioFilter").keydown(function(e){
    $.cookie("fioFilter",$("#fioFilter").val());
});
$("#fioFilter").keyup(function(e){
    window.location.reload();
});

This is my solution. This doesn't works as I want. If I hold key pressed some time it saves in cookies and then reloads. But if I just press one time on key. It reloads and returns old value. What's the problem? http://jsfiddle.net/d6fpfzsu/

Upvotes: 2

Views: 1626

Answers (1)

Ismael Miguel
Ismael Miguel

Reputation: 4241

I got it working on Opera 12.17 on Windows XP

This is my solution:

$(document).ready(function()
{
    var time;
    if($.cookie('fioFilter')!=null)
    {
        $("#fioFilter").focus().text($.cookie('fioFilter'));
    }
    $("#fioFilter").keyup(function(e){
        clearTimeout(time);
        $.cookie("fioFilter",$("#fioFilter").val());
        time=setTimeout(function(){$("#fioFilter").change();},500);
    });
    $("#fioFilter").change(function(e){
        window.location.reload();
    });
});

I got it working by changing from keydown to keyup.

The reload is done on change event, which is triggered after 500ms or when the <textarea> loses focus.
Setting the focus before the value ensures the prompt stays at the end.
This is a "fix" for chrome only.

If there is a cookie set, it will focus the element.

You can check the code here: http://jsfiddle.net/w6hk7w6b/5/

Note

I know I can just set a var and save the selector.

I won't do it for simplicity (and laziness).

Upvotes: 1

Related Questions