[英]Let radio buttons keep value after refreshing
我正在制作一個缺勤控件,您可以在其中使用單選按鈕選擇每個用戶的缺勤情況。 對於每個用戶,您可以選擇存在(“Aanwezig”)、缺席(“Afwezig”)或允許缺席(“Geoorloofd afwezig”)。這意味着一個頁面上有許多單選按鈕。 如果您還沒有按下“保存”並刷新頁面,我想確保輸入不會丟失。 我怎樣才能做到這一點?
我看到 Javascript 有 onkeypress=myFunction(),所以我想,放入單選按鈕可能很有用,但我不知道 myFunction() 應該是什么才能工作......我基本上沒有經驗使用 javascript,我無法在網上真正找到解決方案,因為我沒有看到 Django 的示例。
所以我的問題是:如何確保輸入以某種方式保存,以便在刷新頁面后保持這種狀態?
<form action="{% url 'create_attendance' baksgewijs.id peloton.id %}" method="post">
{% csrf_token %}
<div class="table-responsive fixed-length">
<table id = "userTable">
<tbody>
{% for user in users %}
<tr>
<td> {{ user }}
<td>
<div class="form-check">
<input class="form-check-input" type="radio" name={{user.id}} id="radio" value="Aanwezig">
<label class="form-check-label" for="flexRadioDefault1">
Aanwezig
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name={{user.id}} id="radio" value="Afwezig">
<label class="form-check-label" for="flexRadioDefault2">
Afwezig
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name={{user.id}} id="radio" value="Geoorloofd afwezig">
<label class="form-check-label" for="flexRadioDefault3">
Geoorloofd afwezig
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<input type="submit" value="Sla baksgewijs op" class="btn btn-primary active">
</form>
我認為您正在尋找的是LocalStorage或會話存儲。 html 的狀態將在刷新時恢復為原始狀態,要保存它,您必須保存它的狀態並使網頁做的第一件事就是檢索該狀態。 PS。 這是執行此操作的普通方法
<html> <script> let absent = sessionStorage.getItem('absent'); if(absent){ //absent will be null if there is no saved key in storage let checkbox = document.getElementByName('absent'); checkbox.value = absent; } </script> <form id="mainForm"> <input type="checkbox" name="absent" onchange="(e)=>{ e.preventDefault(); sessionStorage.setItem('absent', e.target.value); }"/>
這可以通過多種方式實現,
1- 如果您想在沒有過期時間的情況下存儲此值,您可以使用Local Storage
。
如需更多資源。
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
2-您可以使用Session Storage
,即使您刷新頁面,該值也會被存儲,但只要瀏覽器選項卡關閉,它就會被刪除。
如需更多資源。
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
3- 您可以使用Cookies
,您可以使用cookies
自己指定到期日期。
如需更多資源。
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.