I am making an absence control where you can select the absence per user with radio buttons. Per user you can select either Present ("Aanwezig"), Absent("Afwezig") or Allowed Absent ("Geoorloofd afwezig").This means that there are many radio buttons on one page. I want to make sure that the input doesn't get lost if you haven't pressed "save" yet and refresh the page. How can I do this?
I saw that Javascript has onkeypress=myFunction(), so I thought, that might be useful to put in the radio buttons, but I don't know what myFunction() should be for it to work... I have basically no experience with javascript and I couldn't really find the solution online, since I saw no examples with Django.
So my question is: How can I make sure that the input gets saved in some way so it stays that way after refreshing the page?
<form action="{% url 'create_attendance' baksgewijs.id peloton.id %}" method="post">
{% csrf_token %}
<div >
<table id = "userTable">
<tbody>
{% for user in users %}
<tr>
<td> {{ user }}
<td>
<div >
<input type="radio" name={{user.id}} id="radio" value="Aanwezig">
<label for="flexRadioDefault1">
Aanwezig
</label>
</div>
<div >
<input type="radio" name={{user.id}} id="radio" value="Afwezig">
<label for="flexRadioDefault2">
Afwezig
</label>
</div>
<div >
<input type="radio" name={{user.id}} id="radio" value="Geoorloofd afwezig">
<label for="flexRadioDefault3">
Geoorloofd afwezig
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<input type="submit" value="Sla baksgewijs op" >
</form>
CodePudding user response:
This can be achieved in multiple ways,
1- You can use Local Storage
If you want to store this value without expiration time.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
2- You can use Session Storage
the value will be stored even if you refresh the page, but whenever the browser tab is closed, it will be deleted.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
3- You can use Cookies
, with cookies
you can specify the expiration date yourself.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
CodePudding user response:
I think what you are looking for is LocalStorage, or Session storage. The state of the html will be put back to original on refresh, to save it you'll have to save its state and make the first thing the webpage does is to retrieve that state. PS. this is the vanilla way to do this
<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);
}"/>