Làm cách nào để bạn có thể làm cho trình duyệt nhớ những gì người dùng đã nhập trong biểu mẫu, chưa được gửi và làm cho trang làm mới không ảnh hưởng đến dữ liệu được nhập?Làm thế nào để nhớ dữ liệu biểu mẫu chưa được gửi?
Tôi có một biểu mẫu mà người dùng nhập một số. Ban đầu, biểu mẫu có 0 theo mặc định. Tôi đang lưu trữ dữ liệu trong localStorage, vì vậy trình duyệt có thể nhớ dữ liệu. Tuy nhiên, khi trang được làm mới, dữ liệu do người dùng nhập sẽ biến mất và 0 được hiển thị theo mặc định. (Vẫn còn dữ liệu localStorage tồn tại cho nó)
Tôi cố gắng để sử dụng jQuery
$(".formClassName").val(localStorage.getItem(key));
nhưng nó không hoạt động. Bất cứ ai có thể cho tôi một lời khuyên về điều này? Cảm ơn bạn trước.
được sửa đổi: hình thức của tôi trông như thế này:
<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>
Và tôi thêm dữ liệu vào localStorage như dưới đây:
//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>
cách thức và thời điểm bạn lưu trữ giá trị trong localStorage? – FabioG
để tôi thêm mã vào câu hỏi. –
là bạn đang thực hiện điều này - '$ (". FormClassName "). Val (localStorage.getItem (key));' sau khi DOM đã sẵn sàng chưa? – Developer