简体   繁体   中英

How to use localstorage to store all checkbox boolean values in a list to an array?

The code looks like this:

<div id="list">
  <input type="checkbox" id="1">
  <input type="checkbox" id="2">
  <input type="checkbox" id="3">
</div>

In another html pane (a separate template), I want to store all those checkbox ( checked / unchecked ) booleans into an array. What I did looks like:

var array = [];
var checkboxli = document.getElementsByTagName("input");
for (var i = 0; i < checkboxli.length; i++)
{
  array.push($("#input.prop('checked')"));
}

However, this doesn't work. I have other templates using tag name " input ", so I need to limit the tag name to the ones under "#list" id (some sort of css selector perhaps). Currently, both document.getElementsByTagName("input") and $("#input.prop('checked')") won't work. There might be other syntax problems. Please help me resolve. Thanks.

EDIT: It seems like I didn't communicate my intention well. Here is what I want to get out of the list: An array that looks like

[true, false, true, true, true...]

in which each boolean value represents whether the corresponding input checkbox is checked or not.

Since your are already using jquery, you can go like this:

Assuming this HTML

<div id="list">
  <input type="checkbox" id="1" checked="checked">
  <input type="checkbox" id="2">
  <input type="checkbox" id="3" checked="checked">
</div>

And this script:

var array = [];
$("input[type='checkbox']","#list").each(function(){
     array.push($(this).is(":checked"));
});

You would get something like this:

array = [ true, false, true ];

Instead of:

var checkboxli = document.getElementsByTagName("input");

you can use:

var checkboxli = document.querySelectorAll("#list>input[type=checkbox]"); //array of checkboxes

now you have all of the checkboxes under the list element.

if you want only the checked checkboxes you can use:

var checkboxli = document.querySelectorAll("#list>input[type=checkbox][checked]"); 

Try below code. It retrieves all IDs from all checked check-boxes , stores in an array and then stores in local-storage as an string :

var itemsChecked = [] ;
$('input[type=checkbox]:checked').each(function(index, item){
   itemsChecked.push($(item).attr('id'));
})

localStorage.setItem('selectedItems', JSON.stringify(itemsChecked));

Later, to retrieved data from localstorage, use the following:

var items = JSON.parse(localStorage.getItem('selectedItems')); 
// returns array of IDs

A more suitable approach would be to capture the XPath of each element starting from the body. You could use a getPath jQuery plugin, Thus you won't be dependent upon a specific string like the List.

jQuery.fn.extend({
    getPath: function( path ) {
       // The first time this function is called, path won't be defined.
       if ( typeof path == 'undefined' ) path = '';

       // If this element is <html> we've reached the end of the path.
       if ( this.is('html') )
           return 'html' + path;

       // Add the element name.
       var cur = this.get(0).nodeName.toLowerCase();

       // Determine the IDs and path.
       var id = this.attr('id'),
           class = this.attr('class');

       // Add the #id if there is one.
       if ( typeof id != 'undefined' )
          cur += '#' + id;

       // Add any classes.
       if ( typeof class != 'undefined' )
          cur += '.' + class.split(/[\s\n]+/).join('.');

       // Recurse up the DOM.
       return this.parent().getPath( ' > ' + cur + path );
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM