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

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

Exploring ways to track file upload progress with the Fetch API in ReactJS or NextJS

Currently, I am utilizing Nextjs for constructing a full-stack application. Specifically, I am focusing on the admin CMS part and attempting to implement file uploads such as images. Referring to this modified version of the code from this post. The upload ...

Utilizing i18n's useTranslation and Redux's connect Higher Order Components to export components efficiently

My application has been utilizing Redux for quite some time, with the component exports structured like this: export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); Now, I am integrating an i18n translation library and would like to use ...

Uncovering unseen glitches while coding in Vue.js

After changing the page, I noticed that the errors from the form are still visible. Is there a way to make them disappear when navigating away and only show up if I return to the page? Here are the errors I am encountering: <template> <b-form @ ...

Stop jQuery from adding duplicate values to a table

When I make an AJAX call using jQuery and PHP to receive JSON response, I am encountering a problem with duplicate values. The code is functioning correctly, but when selecting an option from the drop-down list, duplicate entries appear. The scenario invol ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

Icons that are clickable in ionic

I have successfully created a list card with 2 icons in each row. However, I am facing a challenge in making these icons clickable without disrupting the layout of the list. I attempted to add an ng-click to the icon element, but it did not work as expecte ...

"The issue with AngularJS ng-init, preventing the initialization of a variable at

For my project, I have implemented ng-repeat from the AngularJS directive to display an array containing JSON values with subarrays. <div ng-repeat="data in MENULIST" > //MENULIST contains an array of data I then perform certain conditions checks ...

How can I disable the background color in Chrome autocomplete? Is there a way to make the background

There's a form on my website where the autocomplete feature shows a blue background color. The form itself has a semi-transparent white background. I managed to change the autofill color to white using this CSS property: -webkit-box-shadow: 0 ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...

Mysterious obsidian container lurking in the background of the video on Chrome version 67.0.3396

Displayed on the page is an HTML Video tag, which streams a video from the speaker (WebRTC). <div id="remoteVideoContainer"> <video id="remotevideo" autoplay="autoplay" controls="" loop="loop" preload="true" height="500" width="100%"> ...

Guide to generating a random number asynchronously with AJAX in Django

Apologies for my lack of precision as a beginner, but I hope you can understand my issue. My goal is to return a random value every 1.5 seconds without manually refreshing the browser. The code I currently have works, but I feel like there might be a bett ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

Dilemma: Should calculated table column data be figured out server-side or client-side?

With a table of around 20 columns, half sourced from the database and the other half based on calculated values like "Costs", "Revenue", and "Profit", I'm torn between server-side or client-side calculations. At first, I planned to do the calculations ...

What is the best way to ensure my button displays the complete description of a single country after showcasing all the countries?

I have designed a search feature for countries and I am looking to add a button next to the country names that will trigger one of my components responsible for displaying detailed information about the country. Currently, the details are shown only when t ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...