Tim Mitchell
Tim Mitchell

Reputation: 653

Saving a state within a javascript function

I have a ruby on rails web application that uses a javascript function to update a component on a page.

All I want to do is have the web site 'remember' the value for when the user reloads the page and/or returns after re-loading.

The javascript is very simple. All I want to do is something like this...

$('#my_field').change(function() {
  $('#result').html = 'a new value'
});

only have the 'result' component retain 'a new value' after the user reloads the page.

Any suggestions?

Thanks!

Upvotes: 1

Views: 56

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15393

The html() method sets or returns the content (innerHTML) of the selected elements.

$('#my_field').change(function() {
  $('#result').html('a new value');
});

Upvotes: 1

MShah
MShah

Reputation: 316

I would suggest using HTML5 local storage like so:

This will store a value in local storage localStorage.setItem('value','a new value');

You can now get that value like so: var oldValue = localStorage.getItem('value');

This will work much like cookies, but it is all done client side!

In your example you can use this:

$('#my_field').change(function() {
  localStorage.setItem('value',$('#result').val());
});

When you go the page again after refresh you can get the value:

var oldValue = localStorage.getItem('value');

Upvotes: 2

Related Questions