J P
J P

Reputation: 551

Sending checkbox value to flask

I have a form that looks like this:

<form id="settings" action="{{ url_for("load_settings") }}" method="post">
... 

    <label for="m_r">Interval 1</label>
    <input type="text" name="morn_r" id="m_r">

    <label for="d1_e">Enabled</label>
    <input type="checkbox" name="d_enabled" id="d1_e" value="off" onclick="toggle_check(this)">
</form>

This is the toggle_check function:

function toggle_check(check) {
      if (check.value=="on") {
        check.value="off";
      }
      else {
        check.value="on";
      }
    }

Here's my Python:

@app.route("/settings", methods=["POST", "GET"])
def load_settings():
    if request.method == "POST":
        settings = list(request.form.values())
        print(settings)
    return render_template("settings.html")

If I leave the text inputs empty but click the checkbox, here is what gets printed: [..., '', 'on']

Now, if I also leave the checkbox empty this is what gets printed: [..., '']. For some reason it doesn't add the value of the checkbox...

I don't know how to fix this. Could someone please help?

Thanks.

Upvotes: 0

Views: 3435

Answers (1)

Brad K.
Brad K.

Reputation: 198

Stealing from this answer, the HTML 4 recommendation from W3C states:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

So it's not anything to do with Flask as to why the checkbox value isn't there when unchecked. The browser won't serialize that form input into the request when the checkbox is unchecked.

What you could do though, is give the input some sensible value in the template:

<input type="checkbox" name="d_enabled" value="on">

And then in your Flask handler check for the presence of the value:

if request.form.get('d_enabled') == 'on':
    # checkbox is checked
else:
    # checkbox is not checked

Upvotes: 2

Related Questions