【问题标题】:Save multiple checkbox[] check state on page refresh using local storage in php使用 php 中的本地存储在页面刷新时保存多个复选框 [] 检查状态
【发布时间】:2019-07-16 10:33:03
【问题描述】:

刷新页面后我无法显示用户复选框检查状态。我尝试使用本地存储,但它会检查所有复选框,请帮忙! 我已经使用 ajax 加载不同的页面以通过复选框选择行 这是输入值

<input type="checkbox" id="checkselect" data-name="checkselect[]" class="get_value" value="<?php echo $row['car_booking_id'];?>">

这是我的javascript

   <script>
$('.get_value').on('click', function() {
  var fav, favs = [];
  $('.get_value').each(function() { // run through each of the checkboxes
    fav = {id: $(this).attr('name'), value: $(this).prop('checked')};
    favs.push(fav);
  });
  localStorage.setItem("favorites", JSON.stringify(favs));
  alert(fav);

});

$(document).ready(function() {
  var favorites = JSON.parse(localStorage.getItem('favorites'));
  //alert(favorites);
  if (!favorites.length) {return};
  console.debug(favorites);

  for (var i=0; i<favorites.length; i++) {
    console.debug(favorites[i].value == 'on');
    $('#' + favorites[i].id ).prop('checked', favorites[i].value);
  }
});

</script>

【问题讨论】:

  • 是不是因为所有输入元素都有相同的id
  • @DinoCoderSaurus 我必须将数组中的所有列表保留为 checkselect[] 所以 id 相同

标签: javascript php ajax checkbox


【解决方案1】:

一个使用存储对象跟踪已勾选复选框的简单演示。

这里有一个有用的工厂函数StoreFactory 我写的目的是为了简化对存储对象的进一步处理——它只有很少的方法并且使用起来非常简单。

该演示会生成许多复选框,类似于您在问题中显示的复选框 - 尽管我通过添加唯一的 dataset.id 属性使生活变得更简单 - 这很容易成为实际的 ID,但在问题中它会出现多个复选框将共享相同的无效 ID。

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <script>
            const StoreFactory=function( name, type ){
                'use strict';
                const engine = type.toLowerCase() === 'local' ? localStorage : sessionStorage;
                const set=function( data ){
                    engine.setItem( name, JSON.stringify( data ) );
                };
                const get=function(){
                    return exists( name ) ? JSON.parse( engine.getItem( name ) ) : false;
                };
                const remove=function(){
                    engine.removeItem( name );
                };
                const exists=function(){
                    return engine.getItem( name )==null ? false : true;
                };
                const create=function(o={}){
                    set(o);
                };
                return Object.freeze({
                    set,
                    get,
                    exists,
                    create,
                    remove
                });
            }



            document.addEventListener('DOMContentLoaded', e=>{
                /* create a new storefactory object */
                let store=new StoreFactory('favourites','local');

                /* if the actual store does not exist, create it */
                if( !store.exists() )store.create();

                /* get the data stored in the local storage object */
                let data = store.get();


                /* assign event listeners to all the checkboxes */
                Array.prototype.slice.call( document.querySelectorAll('input[type="checkbox"]') ).forEach( chk=>{
                    chk.addEventListener('click', e=>{

                        /* add checked state to store */
                        data[ e.target.dataset.id ]=e.target.checked;

                        /* save the data */
                        store.set( data );
                    })
                });

                /* reload stored checkboxes */
                Object.keys( data ).map( k =>{
                    if( data[ k ]==true )document.querySelector( 'input[ type="checkbox" ][ data-id="'+k+'" ]' ).checked=true;
                    else {
                        delete data[ k ];
                        store.set( data );
                    }
                })
            })
        </script>
        <style>
            form{ margin:auto; display:flex; flex-diection:row;flex-wrap:wrap; align-items:center;align-content:center;justify:content:center;font-family:cursive }
            label{min-width:4rem;padding:0.5rem;margin:0.25rem;border:1px solid rgba(133,133,133,0.1);box-sizing:border-box;background:whitesmoke}
            label:before{content:attr(data-value);color:blue}
        </style>
    </head>
    <body>
        <form method='post' name='checkboxes'>
        <?php
            /* some checkboxes - note the use of the dataset id attribute! */
            for( $i=1; $i <= 50; $i++ ){
                printf('<label data-value=%d><input data-id="chk_%d" type="checkbox" name="checkselect[]" value="%d" class="get_value" /></label>', $i, $i, $i );
            }
        ?>
        </form>
    </body>
</html>

据我所知,您的代码存在一些小问题。不是jQuery 的用户我可能会弄错,但看起来您获得了对所有复选框的引用,并且无论选中状态如何,都将它们添加到您的favs 数组中,然后将其保存在本地存储对象中。这本身很好,问题围绕fav = {id: $(this).attr('name'), value: $(this).prop('checked')}; 展开~如果有多个选中,则无法判断哪个复选框是哪个。每个复选框都需要一个唯一的 ID(总是如此 ~ ID 属性必须是唯一的!!)

似乎click 处理程序应该在$(document).ready 调用之后定义,然后我想从每个复选框中删除内联onchange="CheckedChange(this)"

稍微重写的代码版本.. 虽然我不知道使用 jQuery data 方法的语法...我想我很接近但它不对所以使用 vanilla js 代替.

<script>
    $(document).ready(function() {
        var favorites = JSON.parse( localStorage.getItem( 'favorites' ) );

        $('.get_value').on('click', function() {
            var favs = [];
            $('.get_value').each(function(){
                favs.push( {
                    id:$(this).attr('data-id'), 
                    value:$(this).prop('checked')
                } );
            });
            localStorage.setItem( 'favorites', JSON.stringify( favs ) );
        });

        if( favorites!==null ){
            for( var i=0; i < favorites.length; i++ ) {
                //$('input').data( 'id', favorites[i].id ).prop( 'checked', favorites[i].value );
                if( favorites[i].value ) document.querySelector( 'input[ type="checkbox" ][ data-id="'+favorites[i].id+'" ]' ).checked=true;
            }
        }
    });
</script>

【讨论】:

  • 我使用了下面的代码,但我的表单是基于 ajax 加载的,所以每当加载新表单时,不会保存复选框状态
  • 这会改变问题的性质,不是吗?也许您应该在原始问题中添加足够的代码来复制该问题。
【解决方案2】:

我认为在您的 html 中,您应该像这样为每个复选框添加一个唯一属性

<input type="checkbox" id="checkselect" data-name="checkselect[]" 
data-unique="<?php echo $row['car_booking_id'];?>" 
class="get_value" 
value="<?php echo $row['car_booking_id'];?>">

现在通过 unique_id 保存检查状态,$('.get_value[data-unique="' + favorites[i].unique_id + '"]').prop('checked', favorites[i].value); 将获取具有该属性的输入,并根据存储的状态将检查设置为打开或关闭

$('.get_value').on('click', function() {
  var fav, favs = [];
  $('.get_value').each(function() { // run through each of the checkboxes
    fav = {unique_id: $(this).attr('data-unique'), value: $(this).value};
    favs.push(fav);
  });
  localStorage.setItem("favorites", JSON.stringify(favs));
  alert(fav);

});

$(document).ready(function() {
  var favorites = JSON.parse(localStorage.getItem('favorites'));
  //alert(favorites);
  if (!favorites.length) {return};
  console.debug(favorites);

  for (var i=0; i<favorites.length; i++) {
    console.debug(favorites[i].value == 'on');
    $('.get_value[data-unique="' + favorites[i].unique_id + '"]').prop('checked', favorites[i].value);

  }
});

请明确指出,使用id 属性对元素进行分组是一种不好的做法。它是为了唯一性,应该这样使用。可以使用classdata-[anything] 属性对元素进行分组。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    相关资源
    最近更新 更多