Well I have this code that changes the colors of a cell, but what I'm looking for is that it doesn't delete the results when I restart the page, because I'm making a page so that users can mark the hours they have available weekly.
I don't know if someone can help me, to save those values, thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script language="javascript" type="text/javascript">
function ilumina(celda){
if (celda.style.backgroundColor=="yellow")
{
celda.style.backgroundColor="green";
}
else
{
celda.style.backgroundColor="yellow";
}
}
</SCRIPT>
</head>
<body>
<table border="1" width="50%">
<tr>
<td bgcolor="green" onclick="ilumina(this)"> </td>
<td bgcolor="green" onclick="ilumina(this)"> </td>
<td bgcolor="green" onclick="ilumina(this)"> </td>
<td bgcolor="green" onclick="ilumina(this)"> </td>
</tr>
</table>
</body>
</html>
You can use
You can save your data each time you change the colors, then on load of the page you can check if you have previously saved any data. If yes, then load the data and change the colors.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script language="javascript" type="text/javascript">
//DOMContentLoaded = when page elements are loaded
document.addEventListener("DOMContentLoaded", function(event) {
//check if we have saved any 'celda_storage_localstorage' value
if ( localStorage.getItem('celda_storage_localstorage') != null ) {
celda_storage = JSON.parse( localStorage.getItem('celda_storage_localstorage') );
//load colors from celda_storage
for (let i=0; i < celda_storage.length; i++) {
document.querySelectorAll('#celdas_table td')[i].style.backgroundColor = celda_storage[i];
}
}
});
function ilumina(celda){
if (celda.style.backgroundColor=="yellow")
{
celda.style.backgroundColor="green";
}
else
{
celda.style.backgroundColor="yellow";
}
//save colors to celda_storage
for (let i=0; i < document.querySelectorAll('#celdas_table td').length; i++) {
celda_storage[i] = document.querySelectorAll('#celdas_table td')[i].style.backgroundColor;
}
console.log(celda_storage);
//JSON.stringify = array to string
localStorage.setItem('celda_storage_localstorage',JSON.stringify(celda_storage));
//JSON.parse = string to array
console.log( JSON.parse( localStorage.getItem('celda_storage_localstorage') ) );
}
</SCRIPT>
</head>
<body>
<table id="celdas_table" border="1" width="50%">
<tr>
<td style="background-color : green" onclick="ilumina(this)"> </td>
<td style="background-color : green" onclick="ilumina(this)"> </td>
<td style="background-color : green" onclick="ilumina(this)"> </td>
<td style="background-color : green" onclick="ilumina(this)"> </td>
</tr>
</table>
</body>
</html>
Have fun and ask !
If I do it with localstorage, it only saves the information for my browser. I think I need to send the information to the backend, but with my knowledge I don't know how to do that.