【问题标题】:Is there a way to preserve html checkbox state after reload in Django?有没有办法在 Django 中重新加载后保留 html 复选框状态?
【发布时间】:2022-01-10 01:41:20
【问题描述】:

示例代码如下。一旦按下提交按钮,我想在页面重新加载后保持选中复选框

<td><input type="checkbox" value="{{ item }}" name="selectedcheckbox"/></td>

【问题讨论】:

    标签: python html django checkbox


    【解决方案1】:

    您可以为此使用 localStorage 全局对象,例如:

    <input type="checkbox" id="checkbox1">checkbox</input>
    <button type="button" onClick="save()">save</button>
    
    function save() {   
        var checkbox = document.getElementById("checkbox1");
        localStorage.setItem("checkbox1", checkbox.checked);    
    }
    
    //for loading
    let checked;
    try {
      checked = JSON.parse(localStorage.getItem("checkbox1"));
    } catch(e) {
      checked = false; // default value on error
      if (typeof e === 'object' && e.message) {
        console.error(e.message)
      }
    }
    document.getElementById("checkbox1").checked = checked;
    

    localStorage 保存在用户的浏览器中,对于最终用户可能登录的所有浏览器,该值不会保持相同

    【讨论】:

    • 你能告诉我如何处理java代码吗?它在 python django 中去哪里?谢谢
    • javascript 代码在 django 的模板中,但会在用户的浏览器中运行
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2023-03-14
    • 2018-01-14
    • 2011-03-19
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多