Ronald Ronald - 4 months ago 6
jQuery Question

localStorage and jQuery Issue

This script below displays the characters remaining (allowable) in a form element (textarea). I want to use local storage to keep the text entered in the textarea until I submit the form.

I am trying to use localStorage so that when I come back to the page - the characters remaining (var text_remaining) doesnt show the full 2000 characters and should only show the characters left...(var text_remaining) ???

<script>

$(document).ready(function() {
var char_th = 2000;
var text_max = 2000;

$('#textarea_feedback').html(char_th + ' characters remaining');
//$('#textarea_feedback').html(text_max + ' characters remaining');

$('#comments').keyup(function() {
var text_length = $('#comments').val().length;
var text_remaining = text_max - text_length;



$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});

</script>


This is what I ended up using
SOLVED - WORKS

<script>

$(document).ready(function() {
var text_max = 2000;

$('#comments').keyup(function() {
var text_length = $('#comments').val().length;

var text_remaining = text_max - text_length;
localStorage.setItem("text", $('#comments').val());

$('#textarea_feedback').html(text_remaining + ' characters remaining');
});


$('#textarea_feedback').html(text_max + ' characters remaining');
var text = localStorage.getItem("text");

$('#comments').val(text);
$('#comments').keyup();

});

</script>

Answer

Try This:

$(document).ready(function() {
  var char_th = 2000;
  var text_max = 2000;
  $('#comments').keyup(function() {
    var text_length = $('#comments').val().length;

    var text_remaining = text_max - text_length;
    localStorage.setItem("text", $('#comments').val());

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
  });
  $('#textarea_feedback').html(char_th + ' characters remaining');
  var text = localStorage.getItem("text");

  $('#comments').val(text);
  $('#comments').keyup();


});
Comments