简体   繁体   中英

How do I store multiple check boxes with local storage

So, to be honest I am going to have a hard time explaining this so I apologize in advanced. Basically I am populating a list of checkboxes with the names of cities. using ajax. What I want to do is allow multiple checkboxes to be checked and store each checkbox value in one single key in local storage. I guess it would look something like this as an example in local storage: city: new york,Los Angeles,Miami. I have tried everything I know and I don't even know how to phrase it in google so if anyone could me that would be great. Ill post my code below.

--This is how I am currently populating the checkbox list:

$(document).delegate("#main", "pagecreate", function () {

    var citySelect = new Array();

    $.ajaxSetup({
        cache: false
    })
    $.ajax({
        url: 'base_city.php',
        data: '',
        isajax: 1,
        dataType: 'json',
        success: function (data) {
            var $city_box = $('#city-selector');

            $city_box.empty();

            for (var i = 0, len = data.length; i < len; i++) {


                $city_box.append("<label for='city_select'><input type='checkbox' name='city_select[]' class='citySelect' value='" + data[i].city + "'>" + data[i].city + "</label>");


            }
        }
    });

});

--This is how I am currently storing the values:

<script type="text/javascript">
                function filterForm() {
                var cityNames = $('.city_select').attr('value');
                localStorage.setItem("city2",  JSON.stringify(cityNames));
                window.location = "#main";  
                location.reload();

            }


            </script>

try to replace

$('.city_select').attr('value');

by

var arr = [];    
$("input[type=checkbox].city_select:checked").each(function(){arr.push(this.value);});

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