Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox?

I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated.

Here is the solution I came up with after some help:

forms.py

from django import forms 
from .models import MyModel

class MyForm(forms.ModelForm):

    class Meta:
            model = MyModel
            fields = [ 
                    'my_checkbox',
                    'my_form_input',
            ]   

index.html

{% load static %}

<html>
        <head>
                <link rel="stylesheet" type="text/css" href="{% static 'my_app/style.css' %}">
                <title>My Django Form</title>
        </head>
        <body>
                <form method="post">{% csrf_token %}
                        {{ form.as_p }}
                        <button type="submit">Submit</button>
                </form> 
                <script src="{% static 'my_app/script.js' %}"></script>
        </body> 
</html>

style.css

#id_my_form_input {
        display : none
}     

script.js

function my_toggle_func() { 
        if (this.checked) {
                document.getElementById("my_form_input").style.display = 'block';
        } else {
                document.getElementById("my_form_input").style.display = 'none';
        }
}

document.getElementById("my_checkbox").onclick = my_toggle_func;

Answer №1

If you find yourself in a situation where you require Javascript instead of Django, it's likely because Django is limited to backend operations and cannot directly handle changes on the front-end. To address this issue, consider using Javascript (such as jQuery) to detect changes in checkbox states and make corresponding form fields visible without the need for backend interaction. You can initially render the form field invisibly with Django using <input type="hidden> and then use Javascript to reveal it when necessary.

However, if backend interaction is necessary, a similar approach can be taken. Render the page with Django, monitor checkbox changes, and upon detection of a change, send an AJAX request to a Django view that processes the request and returns the required data (e.g., from a database or complex calculations). Django’s JsonResponse can be utilized to return this data seamlessly to the front-end.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

The Django Bootstrap CSS file seems to be missing as it is returning a

I ran into an issue while trying to incorporate bootstrap into my HTML page. The network tab in the developer tools displayed a 404 status code, indicating that the file could not be found. The request URL is: Below is the snippet of my HTML page where I ...

Extract the array of numbers from the JSON file

My task is to extract an array of numbers from JSON files. I need to handle files that contain only arrays of numbers or one level deeper (referred to as direct arrays). These files may also include other data types such as strings or booleans. The challe ...

React maintains the state of just a single element within an array at a time

I'm faced with a roadblock while developing my covid19 application. The app should display a list of countries on the left side of the screen, allowing users to add any number of countries to the right side for more detailed covid data. I'm still ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

The amalgamation of geometries using BufferGeometryUtils results in variations from the original model

I have encountered an issue when attempting to merge GLB model geometries with three.js using BufferGeometryUtils.mergeBufferGeometries. The new merged geometries do not always align perfectly with the original model. Furthermore, some of the geometries e ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

Error: The module '../lib/cli' could not be located

As someone new to the world of JavaScript development, I'm encountering an error while working through the backbone_blueprints book. Here's the specific error message I've come across: > <a href="/cdn-cgi/l/email-protection" class="__ ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Connecting factors

Let me simplify what my code does: var list = { "group":{ "subgroup1":[{"name1":"Jimmy","name2":"Bob"}], "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}] } } function group(group,name){ var link ...

"Concealing tooltip boxes in Vue: A step-by-step guide

I am trying to achieve a functionality where a tooltip box appears on each incorrect or empty input field when the 'Save' button is pressed. I have been able to display the tooltip boxes upon clicking the 'Save' button, but the issue ar ...

Waiting for Angular's For loop to complete

Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them ...

The Google Geo Charts fail to load when initiated by Ajax requests

My goal is to use ajax to load an external HTML page that includes the following code: <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type='text/javascript'> function ...

Assigning a value to a cell depending on a specific condition

Currently, I have a column connected to a field known as state. The possible values for this field are either S or L. My objective is to map these values as follows: S => Short, L => Long The binding is structured in the following way: $scope.grid ...

Ways to prevent a floated element from impacting text-align: center styling?

Within my code, there is a <p> element structured as follows: <div><p>Text Goes Here <span></span</p></div> The CSS I currently have is: div { text-align:center } span { float:right } An issue arises when I populate ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...

Tips for retrieving corresponding values from a TypeScript dictionary object?

I am currently working with a dictionary object that is filled in the following manner: const myDictionaryElement = this.myDictionary["abc"]; In this case, myDictionaryElement contains the values: ACheckStatus: "PASS" QVVStatus: "READY" VVQStatus: "READ ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...

Occasionally, adding items to an array through pushing may not be successful

Here is a snippet of HTML code: <select name="region-select" id="regions-select" class="form-control"> <option selected=""> </option> <option value="23">Name1</option> <option value="24">Name2</option> ...