W jaki sposób można sprawić, aby przeglądarka zapamiętała, co użytkownik wpisał w formularzu, który nie został jeszcze przesłany i czy odświeżenie strony nie ma wpływu na wprowadzone dane?Jak zapamiętać dane formularzy, które nie zostały przesłane?
Mam formularz, w którym użytkownik wprowadza numer. Początkowo formularz ma domyślnie wartość 0. Przechowuję dane w localStorage, aby przeglądarka mogła zapamiętać dane. Jednak po odświeżeniu strony dane wprowadzone przez użytkownika znikają, a domyślnie wyświetlana jest wartość 0. (Wciąż dane localStorage istnieje dla niego)
Próbuję użyć jQuery
$(".formClassName").val(localStorage.getItem(key));
ale to nie działa. Czy ktoś może mi doradzić? Dziękuję z góry.
Zmieniano: Moja postać wygląda następująco:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
I dodaję dane do localStorage jak poniżej:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
jak i kiedy przechowujesz wartość w localStorage? – FabioG
pozwól mi dodać kod do pytania. –
Czy wykonujesz to - '$ (". FormClassName "). Val (localStorage.getItem (key));' after DOM ready? – Developer