Solution 1 :

There are two ways to solve this kind of issues, by keeping track of posted data in the Django view, or using ajax to send data to view, preventing html page and thus form to reload each time the post is sent.

1. Keeping track of posted data:

In your view, you should get checkbox states in the posted data, by getting list of checked values of your checkboxes and then return them as context data. It depends how your response is organized, but for simplicity let us assume you use TemplateResponse:

return TemplateResponse(request, 'your.html',{'checked_hms':request.POST.getlist('hm')})

Than in your html you should use condition to check if value exists in checked_hms and based on add checked value to your checkbox inputs, like this:

...
<input type="checkbox" class="form-control" id="one" name="hm" value="one" {% if 'one' in checked_hms %}checked{% endif %} onchange="triggerPost()">
<label for="one">One</label>
<br>
<input type="checkbox" class="form-control" id="two" name="hm" value="two" {% if 'two' in checked_hms %}checked{% endif %} onchange="triggerPost()">
<label for="two">Two</label>
...

2. Using ajax:

You may send form data as post, using ajax call, which will not reload form, thus keeping checkboxes states intact, something like this:

<script>
    function triggerPost() {
        $.ajax({
            type: "POST",
            url: $('#hostform').attr('action'),
            data: $('#hostform').serialize()
        });
    };
</script>

Problem :

When one or more of the checkboxes in hostform are checked, I want to trigger a form submit. This is triggered successfully with the code below. However, the page reloads on the form submit, making any box that is checked go immediately back to being unchecked. I thought the localStorage.input line would fix this, but apparently not.

Any suggestions?

HTML:

<div class="container-lg">

      <!-- section for checkboxes -->
      <div class="row justify-content-center">
        <div class="col-6">
          <h2>Host</h2>
          <form id="hostform" class="form-inline" role="form" action="" method="post">
            {% csrf_token %}
            <input type="checkbox" class="form-control" id="one" name="hm" value="one" onchange="triggerPost('one')">
            <label for="one">One</label>
            <br>
            <input type="checkbox" class="form-control" id="two" name="hm" value="two" onchange="triggerPost('two')">
            <label for="two">Two</label>
            <br>

          </form>

        </div>

     ....
     </div>

jQuery:

<script>
  function triggerPost(idnum) {
    
    $('#hostform').on("submit", function () {
      localStorage.input = $("#"+idnum).checked;
    });
    $('#hostform').submit()
  };
</script>

Comments

Comment posted by Charly Phillips

Using ajax as suggested worked great! Thanks

By