Search code examples
flaskpostcheckboxgetwebserver

Flask keeping checkboxes after page regresh


I have this piece of code of a flask template

<div class="rows">
     <h3>In oven</h3>
     {% for checkbox in checkboxes: %}
     <li><input type="checkbox"></li>
     {% endfor %}
</div>     

I tried using java script but after refresh the checkboxes resets even if I checked it before. I want to checked it and after refreshing the page the check to stay. Any ideas how to do it?


Solution

  • You need to store somewhere the value of the checkbox to set it when loading the page again.

    • Local storage
    • Flask session
    • Database
    • Ajax query
    • With a form

    This value has to be something that can be evaluated as true/false.

    After retrieving the value you need to evaluate for add or not the checked property in the input.

    In this example, I'm using a variable on the view.

    #app.py
    @app.route("/")
    def sample():
        your_variable=True
        return render_template('index.html', your_variable=your_variable)
    
    #index.html
    <div class="rows">
         <h3>In oven</h3>
         {% for checkbox in checkboxes: %}
         <li><input type="checkbox" {{'checked="checked"' if your_variable else ""}}></li>
         {% endfor %}
    </div>     
    

    Of course, with a more complete question this can be more specific