user3927582
user3927582

Reputation: 189

Can you use jquery in sessionStorage?

I have code like this:

$(document).ready(function() {

var field = $('#field').val();

if (sessionStorage.getItem('save')) {
    $('#field').val(sessionStorage.getItem('save'));
}

field.addEventListener("change", function() {
    sessionStorage.setItem('save', field);
});

});

<input id="field" type="text"></input>

http://jsfiddle.net/oae8krpm/

But it doesn't seem to work with jQuery, can it?

Thanks

Upvotes: 0

Views: 2093

Answers (1)

bobince
bobince

Reputation: 536755

field.addEventListener

field is the text value of the field, not the DOM object for the field. Use $('#field').get(0).addEventListener, or just jQuery event handling (on et al).

sessionStorage.setItem('save', field);

field is the text value of the field at the point you read it on document-ready. If you want to store the new value it was changed to, you'll need to read it again:

$('#field').on('change', function() {
    sessionStorage.setItem('save', $('#field').val());
});

Upvotes: 3

Related Questions