3

I'm using jStorage to store the value of an input, when I click the save button. Then I want to set the stored value as the current input value on page load. It ain't working too well though.

HTML

<input type='text' id='name'>
<div id="save">Save</div>

JS

$('#save').click(function() {
  $.jStorage.set("key", $("#name").val());
});

var input_value = $.jStorage.get("key");
colmtuite
  • 4,311
  • 11
  • 45
  • 67

1 Answers1

4

It's a little tangled up:

$.jStorage.set("key", $("#name").val());

var input_value = $.jStorage.get("key");

When you're passing a selector to jQuery you have to pass a valid string, not just the raw CSS selector syntax. That is, you've got to get the selector expression into JavaScript first, and you do that by creating a string constant.

edit — If you want your <input> to show the last-saved value when the page loads, you'd do something like this:

$(function() {
  $('#name').val( $.jStorage.get("key") || "" );
});

Wrapping the activity in a $(function() { ... }) wrapper ensures that the code won't run until the <input> field has been seen and parsed by the browser, but still very soon after the user sees the page load (essentially immediately).

Adding the extra || "" bit after the jStorage call ensures that if the value is null or undefined the user won't see that. If there's no stored value, in other words, that'll have the input just be empty. You could put any other default value in there of course.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks mate. I've edited my question because I wanted to store the value of the input when I click the save button, then load the stored value everytime I refresh the page. Any ideas? – colmtuite Nov 30 '13 at 23:20
  • @Moppy ok I *think* I know what you mean - you want the input to have the saved value whenever the page initially loads, right? I'll add to the answer. – Pointy Nov 30 '13 at 23:54