Home > Back-end >  How to transmit "metadata" of an HTML-element to a function? / Individual ID for HTML elem
How to transmit "metadata" of an HTML-element to a function? / Individual ID for HTML elem

Time:03-13

My title might be a bit confusing... This is my first attempt (ever) for a webapp and I got the following solution for a set of checkboxes, created within a html template for FastAPI and with Jinja2.

{% for name in names %}
    <input type="checkbox" id='{"box": "a", "name_id": "{{name.id}}"}' onchange=submit_me(this)>
    <input type="checkbox" id='{"box": "b", "name_id": "{{name.id}}"}' onchange=submit_me(this)>
{% endfor %}

<script>
    function submit_me(box){
        data = JSON.parse(box.id)
        data["checked"] = box.checked
        
        fetch("/test", {
            method: "PUT",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
        })
    }
</script>

This is just a simple example of a more complex code but shows my (inexperienced) solution for the problem to get the box ("a" or "b") as well as the name (iteration of names via jinja) inside my function. I was just wondering, if this is really a valid option or if there is a way more "standard" approach for this out there?

This is - by the way - only the "quick and dirty" solution because I was unable to call a python function via jinja and FastAPI directly (html -> python backend -> database)

CodePudding user response:

This is not what an element's id should be used for. If you need to attach random data to an element, use the data- attributes. input elements have the name attribute and value attribute that should be used to describe the value, and the actual value. No need to stuff JSON inside id (which should be a unique identifier for an element in a document).

Submitting data by checking a checkbox also seems wrong (generally, depends on your use case) - use a form element if you have data you want to submit, and submit when a button is clicked.

Since you have hardcoded values (a, b), using iteration also seems a bit weird:

<input type="checkbox" name="box_a" id="box-a" value="{{ names[0].id }}" onchange="submit_me(this);">

<input type="checkbox" name="box_b" id="box-b" value="{{ names[1].id }}" onchange="submit_me(this);">

However, if you have a / b stored inside your name object, use iteration and have a single element where you fill out the information as necessary in the tag:

<input type="checkbox" name="box_{{ name.key }}" id="box-{{ name.key }}" value="{{ name.id }}" onchange="submit_me(this);">
  • Related