1
I’m trying to keep the checkbox selected even after refreshing on the page, this is my progress:
// javascript
var s_item = "";
function save(items) {
s_item = items;
var checkbox = document.getElementById(s_item);
localStorage.setItem(s_item, checkbox.checked);
return s_item;
}
function load() {
if (s_item != "") {
var checked = JSON.parse(localStorage.getItem(s_item));
document.getElementById(s_item).checked = checked;
}
}
load();
// html
<input id="@item.Id" type="checkbox" onclick="save('@item.Id');">
In the checkbox, I am trying to pass as parameter an id of each checkbox I have with an event onclick()
and record them in localStorage
, I do not know if this is the best way to solve my problem however, it is not working because it is giving error with the global variable "item" always looks like null
.
I’m wearing a foreach
to check in asp.net mvc
.
Basically I just need these selected checkboxes to remain selected after a page re-load.
Friend, it worked, however, only when I put the script inside my loop, because @item.id only exists inside the foreach, which is like this:
@foreach (var item in Model){<td>dados</td>
<td><input id="@item.Id.@idcheck" type="checkbox" onclick="save(this)"></td>}
I put an idcheck variable outside the loop, then incremented each item inside the loop and put as key of the localstorage, it worked, but I only managed to put all the script inside the loop. would have some way of doing that by catching the item id. out of the loop and passing to the function?– haveros