Form input with Htmx

February 4, 2023

Htmx allows you to develop dynamic, interactive web pages without complex JavaScript. The example below uses Htmx in a Flask app to submit a form when the page loads. Results calculated from the form values are displayed on the same page.

form htmx


from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

def index():
    return render_template('index.html')

@app.route('/results', methods=['POST'])
def results():
    values = request.form['values']
    multiplier = request.form['multiplier']

    vals = list(map(int, values.split(', ')))
    mult = int(multiplier)

    y = []
    for val in vals:
        y.append(val * mult)

    return render_template('results.html', results=y)

The main webpage index.html is shown below. Notice the use of Htmx to handle the form submission when the page loads and when the user clicks the submit button.

<!-- templates/index.html -->

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Home Page</title>
    <div class="container">
        <div class="row">

            <div class="col">
                <h1 class="mt-3">Submit values</h1>

                <p>Input using comma separated values then click the submit button to see results.</p>

                <form hx-post="/results" hx-target="#results" hx-trigger="load, submit">
                    <div class="mb-3">
                        <label for="values" class="form-label">Values</label>
                        <input type="text" class="form-control" style="max-width:200px;" name="values" value="1, 2, 3, 4, 5">
                    <div class="mb-3">
                        <label for="multiplier" class="form-label">Multiplier</label>
                        <input type="text" class="form-control" style="max-width:200px;" name="multiplier" value="3">
                    <button type="submit" class="btn btn-primary">Submit</button>

            <div class="col">
                <div id="results"></div>


    <script src="" integrity="sha384-tvG/2mnCFmGQzYC1Oh3qxQ7CkQ9kMzYjWZSNtrRZygHPDDqottzEJsqS4oUVodhW" crossorigin="anonymous"></script>

<!-- templates/results.html -->

<h1 class="mt-3">Results</h1>

<p>Below are the results using the form inputs.</p>

{% raw %}{{ results }}{% endraw %}