I'm trying to persist form data into localStorage. For regular HTML fields like textboxes, this works perfectly. However I have a couple of rich text fields that don't seem to be able to save their data.
Razor markup for the field (I'm using MVC)
<div class="form-group">
@Html.LabelFor(model => model.Actions, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextAreaFor(model => model.Actions, new { @class = "form-control", rows = "4" })
@Html.ValidationMessageFor(model => model.Actions, "", new { @class = "text-danger" })
</div>
HTML markup generated by the above:
<div class="form-group">
<label class="control-label col-md-2" for="Actions">Actions</label>
<textarea class="form-control" cols="20" id="Actions" name="Actions" rows="4">
</textarea>
<span class="field-validation-valid text-danger" data-valmsg-for="Actions" data-valmsg-replace="true"></span>
</div>
Here is the code for saving / retrieving from local storage. I'm using exactly the same method for other fields and it works perfectly.
//save
localStorage.setItem('Actions', document.getElementById('Actions').value);
//restore
var Actions = localStorage.getItem('Actions');
document.getElementById('Actions').value = Actions;
I've tried using document.getElementById('Actions').textContent
rather than .value
- this seems to make it save correctly but I still can't restore the text. When I look at the localStorage
object though it only reports the following text in my Actions field: "<p><br></p>"
, unless using .textContent
, in which case I see something like <p>Test text<br></p>
I am using Summernote to provide rich text functionality and think this might be the cause of the issue but I'm not sure what to try. There are no errors reported in the console at all.
I fixed this by using the following code
$('#Actions').summernote('code', Actions);
in place of
document.getElementById('Actions').value = Actions;
This puts the html code from the field directly into the summernote textarea with all formatting etc. I was also able to use .actions
(.innerhtml
didn't work)