如何在刷新页面后保持单个复选框的选中状态?

6

HTML代码:

    <div class="wrap">
        <h3>Background Swap:</h3>
        <form action="" method="POST">
            <div id="checkbox-container">
                Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
            </div>
            <input type="submit" name="submit" value="Upgrade Background" class="button" />
        </form>
    </div>

这将使复选框保持选中状态,但当页面刷新或退出并返回时,复选框将取消选中。因此,在进行了一些研究后,我尝试使用localStorage,但似乎还没有完全弄清楚。 localStorage代码:
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function(){
        $checkbox.each(function(){
            checkboxValue[this.id] = this.checked; 
        });
        localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value){
        $("#" + key).prop('checked', value);
    });

我有localStorage代码周围的脚本标签,并在实现这些代码后,我的复选框仍然无法保持选中状态。

两个代码整体如下:

<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
    <div id="checkbox-container">
        Background Swap: <input type="checkbox" name="new_background"/>
    </div>
    <script>
        var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
        var $checkbox = $("#checkbox-container :checkbox");

        $checkbox.on("change", function(){
            $checkbox.each(function(){
                checkboxValue[this.id] = this.checked; 
            });
            localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
        });

        //on page load
        $.each(checkboxValue, function(key, value){
            $("#" + key).prop('checked', value);
        });
        </script>
        <input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>

我想感谢所有花时间帮助我解决问题的人,特别鸣谢 @Pranav C Balan!请查看完整的代码 @ https://dev59.com/UaLia4cB1Zd3GeqPfz29#44321072

乍一看你的代码似乎没问题。你能验证一下 checkboxValue 是否具有你期望的值吗?在你勾选复选框并重新加载页面后,它是否仍然保持原来的值? - Halcyon
@DanielH 是的,我只有一个复选框。 - Kong Meng Xiong
你的页面中代码放在哪里? - Pranav C Balan
@Halcyon 我不确定我能否做到,但我正在尝试的是,在勾选复选框后,它会将信息发送到我的数据库表并更改列的值。它确实更改了值,但在刷新页面或离开然后返回页面后,复选框未被选中。 - Kong Meng Xiong
@PatrickBarr 是的,它在复选框下面,如果我移除了jQuery,复选框仍然存在。 - Kong Meng Xiong
显示剩余6条评论
5个回答

1
我认为您的代码在表单元素加载之前执行,因此请将其放置在代码末尾或使用文档准备好处理程序进行包装,以便仅在元素加载后执行。如果您将代码放置在元素之前$("#checkbox-container :checkbox")将选择无效,因为它尚未加载到DOM中。
还有一件事要做,在您的代码中,复选框没有任何id,因此请添加唯一的id以使其起作用,因为JSON是使用id值生成的。
<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>
  <script>
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  </script>
</div>

工作演示:FIDDLE
<script>
  // document ready handler
  // or $(document).ready(Function(){...
  jQuery(function($) {
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  });
</script>
<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>

</div>

工作演示:FIDDLE

1
@KongMengXiong:很高兴能帮助你 :) - Pranav C Balan

0

一种替代localStorage的方案,只使用document.cookie:

$('input:checkbox').change(function() {
    saveCookies();
});

注册函数和实际函数:

function saveCookies() {
    var checkArray = [];
    $('input.comic-check').each(function() {
        if ($(this).is(':checked')) {
            checkArray.push(1);
        } else {
            checkArray.push(0);
        }
    });
    document.cookie = "checks=" + checkArray;
}

这是localStorage的替代方案,取决于您是否希望它持久存在。

并且可以检索已保存的内容(在加载时)。

var checks = getCookie("checks");
if (checks != "") {
    checkArray = checks.split(',');
    //unchecks boxes based on cookies
    //also has backwards compatability provided we only append to the list in landing.ejs/generator.js
    for (var i = 0; i < checkArray.length; i++) {
        if (checkArray[i] == "0" && $('input.comic-check').length > i) {
            var checkBox = $('input.comic-check')[i];
            $(checkBox).prop('checked', false);
        }
    }
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

谢谢,但似乎它并没有起作用,或者我没有正确实现。 - Kong Meng Xiong

0

我会改变:

<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>

for:

<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>

在内联HTML中,您不需要将checked属性设置为checked=checked
只需使用checked即可。

checked=checked用于JavaScript编程中以编程方式选中复选框。

编辑
关于您的localStorage...

我为您在CodePen上制作了一个示例。

//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
  $("#" + key).prop('checked', value);
});

// ================ Saving checks

// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");

// On change handler.
allCheckboxes.on("change", function() {

  // Check how many checkboxes we have.
  var jsonCheckboxes = {};
  console.log("There is "+allCheckboxes.length+" checkboxes.");

  // Building the json.
  for(i=0;i<allCheckboxes.length;i++){
    console.log(allCheckboxes.eq(i).attr("id"));
    console.log(allCheckboxes.eq(i).is(":checked"));
    jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
  }
  console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));

  // Setting localStorage.
  localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
  console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});

@KongMengXiong:您加载了jQuery库的Fiddle运行得非常好。在这里查看更新内容(https://jsfiddle.net/Bes7weB/o3f5928u/)。请注意,它在加载时是“未定义”的...因为还没有存储。但是选中复选框并提交。然后重新加载Fiddle。 - Louys Patrice Bessette
是的,我知道我可以直接设置复选框为“已选中”,但问题是如果用户取消选择它,它就不会保持未选中状态。如果该框被选中,则在按下“更新背景”按钮后将1传递到数据库表中,否则传递0表示未选中。 - Kong Meng Xiong
我编辑了一个有关LocalStorage的工作示例。;) - Louys Patrice Bessette
我能把这两段代码合并到同一个文件中吗,还是需要两个单独的文件? - Kong Meng Xiong
如果您提交“to self”,则不需要使用PHP代码,因为数据存储在本地并有一个脚本来使用它。如果您想摆脱localStorage和JS脚本,则可以使用PHP完成。所以这是二选一。由您决定。两者都可以完成相同的事情。;) - Louys Patrice Bessette

0

三种情况下你需要勾选复选框

  1. PHP将其设置为checked="checked"(已选中)

  2. localStorage将其设置为true(已选中)

  3. 所有其他情况下都应取消勾选

你只需确保前两种情况下勾选复选框,然后默认情况下它未被勾选,但在每个中,你也取消勾选复选框,因此忽略了PHP部分(因为PHP将其设置为已选中,但localStorege将其设置为未选中)

示例:https://jsfiddle.net/dalinhuang/efwc7ejb/

//on page load
$.each(checkboxValue, function(key, value) {
    if(value){
       $("#" + key).prop('checked', value);
    }
});

如果我想要一个单选框,我该如何更改localStorage代码? - Kong Meng Xiong
@KongMengXiong 如果你只有一个单选框并且知道它的ID,你可以直接使用以下代码 https://jsfiddle.net/dalinhuang/dehcunxL/ - Dalin Huang
是的,我知道我可以直接设置复选框为已选中,但问题是如果他们取消选择它,它不会保持未选中状态。如果该框被选中,则在按下“更新背景”按钮后将1传递到数据库表中,否则传递0表示未选中。 - Kong Meng Xiong
@KongMengXiong,你只想遵循localStorage吗?如果localStorage已经设置了true/false,那就忽略php吧。 - Dalin Huang
我的目标是找到一些方法,使得如果用户选择了复选框,则它会保持选中状态,因此如果您认为其他东西更有效率,例如cookie,那么它不必是localStorage。 - Kong Meng Xiong

0

针对您的评论:我的目标是找到一些东西,如果用户选择了,它将使我的复选框保持选中状态,这里有一种方法可以使用localStorage来处理:

jQuery(3.2.1)

$(document).ready(function() {

var bground = localStorage.getItem('background'); // get the value if exists

if (bground == 'shadow') { // checkbox has been previously checked
    $('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
    $('#checker').attr('');
}

$('#submit').submit(function() { // when form is submitted
    bground = localStorage.getItem('background'); // get the value in LS
    if($('#checker').is(':checked')) // is it checked or not ?
    { sh = 'shadow'; } else { sh = 'shadowless'; }
    localStorage.setItem('background', sh); // update LS with new value
}); 

});

HTML(在表单中添加id="submit"
<form action="" id="submit" method="POST">
  <div id="checkbox-container">
  Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
  </div>
  <input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>

这将使复选框保持选中状态,当页面刷新时,复选框将根据用户先前的选择而被选中/取消选中。

您还可以使用jQuery的change函数而不是表单提交。只需修改以下行:

$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line

谢谢,但是它对我似乎不起作用。也许我输入有误。还是谢谢! - Kong Meng Xiong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接