Friday, 28 August 2020

how to save checked checkboxes after reloading data using ajax call

I defined a dropbox selector which after selecting a country gives me a list of cities as checkboxs. I am using jquery and ajax to preview it and select it as follow.

<div>
    <div id="preview-items">
    </div>
</div>

<script>
     $("#id_country").change(function () {
          var countryId = $(this).val();  // get the selected country ID from the HTML input

          $.ajax({  // initialize an AJAX request
            url: '/ajax/ajax_load_cities',
            data: {
                 'countries': countryId   // add the country id to the GET parameters
            },
            dataType: 'json',
            success: function (data) { // `data` is the return of the `load_cities` view function
             $('#preview-items').html('');
    
             for (var i in data.tags) {
                   $('#preview-items').append(`
                       <label class="btn btn-primary mr-1"> 
                       <input type="checkbox"  id="checklist_` + data.tags[i][0]+ `" value="` + data.tags[i][0] + `"> 
                       <span> 
                         ` + data.tags[i][1] + ` 
                       </span> 
                       </label><br />` 
                    ).find("#checklist_" + data.tags[i][0]).on("change", function(e){

                    var cities_array = $(":checkbox:checked").map( function() { return $(this).next().html(); }).get();
                    $("#preview-items").html(cities_array.join(', '));

                   if (e.target.checked) { 
                       localStorage.checked = true;
                    } else {
                        localStorage.checked = false; 
                    } 

              }
            }
           });
      });
</script>

and in django view.py:

def load_cities(request):
    ....
    
    data = {
        'tags': list(cities)
    }
    return JsonResponse(data)

The problem is that, it does not keep the selected cities after changing the country selectors. after googling, I found that cookies are a good choice. I wanted to know how to save selected checkboxes when dropbox items change?



from how to save checked checkboxes after reloading data using ajax call

No comments:

Post a Comment