Using Django Crispy forms to dynamically hide fields based on the value of another field

What is the best way to dynamically hide or show a form field in Django crispy forms depending on the selected value of another field in the form?

For example: Field A contains a dropdown menu with options '1' and '2'. Field B should be displayed when Field A is set to '1'. Field C should be displayed when Field A is set to '2'. All other fields should remain visible in their default state.

I have experimented with various query and JavaScript solutions found on forums, but none of them seem to work correctly with crispy forms.

Links to related forum discussions: Link1, Link2, Link3

It is possible that I am misinterpreting the solutions provided or that they are not compatible with Crispy forms.

Models.py

class TestCondition(models.Model):
    some_name = models.ForeignKey(key_name, on_delete=models.CASCADE)
    A_type_choices = (
        ('1','1'),
        ('2','2'),
    )
    Field_A = models.CharField(max_length=20,choices= A_type_choices,default='1')
    B_field_choices = (
        ('abc','ABC'),
        ('cba','CBA'),
    )
    Field_B = models.CharField(max_length=20,choices= B_field_choices,default='abc',blank=True,)
    Field_C = models.CharField(max_length=40, blank=True, default='')

views.py

class ViewUpdateTestCondition(LoginRequiredMixin,UpdateView):
    model = TestCondition
    template_name = 'update.html'
    form_class = TestConditionForm

class TestConditionForm(ModelForm):
    class Meta:
        model = TestCondition
        fields = ('some_name','Field_A','Field_B','Field_C')
    def __init__(self, *args, **kwargs):
        super(ModelconfigForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(form=self)
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-8'
        self.helper.form_method = 'post' 

        self.helper.layout = Layout(
            Fieldset(
                'Test Condition',
                Field('some_name', type='hidden'),
                ('Field_A','Field_B','Field_C')),
            FormActions(
                Submit('submit', "Save changes")
            )   
        )

Update.html

{% extends 'base.html' %}
    {% load static %}
    {% block content %}
            <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
         <script src="{% static 'formset/jquery.formset.js' %}"></script>
        <script>
    function Hide() {
        if(document.getElementById('id_Field_A').options[document.getElementById('Field_A').selectedIndex].value == "1") {
             document.getElementById('id_Field_B').style.display = 'none';
             document.getElementById('id_Field_C').style.display = '';
        } else {
             document.getElementById('id_Field_B').style.display = '';
             document.getElementById('id_Field_C').style.display = 'none';
        }
    };  </script>
         {% load crispy_forms_tags %} 
         {% crispy form form.helper%}
{% endblock %}

Answer №1

Thank you art06! I applied the changes you suggested and it's working perfectly.

<script type="text/javascript"> window.addEventListener("load", Hide);</script> <script type="text/javascript"> var element = document.getElementById("div_id_Field_A"); element.addEventListener("click", Hide);</script> 

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

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

What is the best way to access the following element of an array within a for..of loop with an if statement in Javascript?

Need help with creating a word filter that checks if index 1 is 'dog' and index 2 is 'cat' in an array. What should be checked in the next index for 'word'? let textContainer = ['bird', 'dog', 'cat& ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Combining two arrays in React using TypeScript and showcasing them in a single list display

I am working on a React TypeScript project and have two comma-separated strings that I am converting into arrays. One array contains the file names, and the other contains the file link paths. My goal is to merge the two arrays so that the first item in th ...

Layout display issue post redirection in React

I am facing an issue with my app that utilizes styled-components and material-ui. I have set up private routes based on user roles, and when a non-authenticated user is redirected to the login page, the layout fails to load properly. App.tsx import React ...

Employing buffers and streams for data transmission

I am in need of a node.js program that can effectively handle a large JSON dataset with thousands of records. Specifically, I require a script that can extract only the "name" key from each record and transfer it to another file using streams. If there ar ...

The sequence of Angular directives being executed

When multiple directives are applied to an element in AngularJS, what determines the order in which they will be executed? For instance: <input ng-change='foo()' data-number-formatter></input> Which directive, the number formatter ...

Optimizing AngularJS performance with REST service caching

My AngularJS application requires caching of REST service responses, and I've come across libraries like angular-cached-resource that store data in the local browser storage. However, there are times when certain cached responses need to be deleted d ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

Error message: Unable to access $controller with AngularJS and Karma

As someone who is just starting with testing, I figured it was a good idea to begin testing this project. However, when I execute grunt karma:watch, I encounter an error related to the configuration files. My config file includes: module.exports = functi ...

How can you exhibit various images without relying on the <img> tag?

Is there a more efficient way to display over 500 images from a folder on an HTML page without the need to manually write out each img src tag? I have searched online for solutions, but most suggestions involve using PHP or "glob", which I am hesitant to ...

Struggling to access component variables within the setTimeout function

As a newcomer to Angular(6), I am facing an issue where I am unable to access component variables within a setTimeout function. Below is the code snippet illustrating my problem. export class ConSellerDraftsolSecOneComponent implements OnInit { ...

Matching words with their meanings - exploring storage possibilities

I want to create a system to store vocabulary words and their translations in an organized manner... One idea I had was to use an associative array where each object represents a word and its translation. var vocab = []; vocab.push({"chinese" : "Nǐ", "e ...

I am utilizing client-side JS to send a large number of requests. What methods can I implement to enable my server to cache this content

Here's a bit of an unusual question from someone who is new to this - I have client-side JavaScript that is making API calls using the getJSON method. Since the content doesn't change frequently, I would like to store the results on my server an ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

Having trouble with `request.auth.session.set(user_info)` in HapiJS?

I've encountered an issue with my strategy that is defined on a server.register(). Although I followed a tutorial, the code seems to be copied verbatim from it and now it's not functioning as expected. server.auth.strategy('standard&apo ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

Is there a way to dynamically update text using javascript on a daily basis?

I am currently developing a script to showcase different content and images every day. While I have successfully implemented the image loop to display a new picture daily, I need assistance in achieving the same functionality for the title. My aim is to c ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...