Steven Eckhoff Steven Eckhoff - 24 days ago 8x
CSS Question

Make HTML form text field presence dependent on checkbox selection using Django, CSS, and Javascript

I have a Django form and I would like it to initially hide a text field until the user selects a checkbox.

I am new to Django and web applications, so I have no idea what I am looking for or what it is called. I have searched to no avail. Any pointer would be helpful.


Thanks for the help makaveli. Below is my first stab at this:

from django import forms
from .models import MyModel

class MyForm(forms.ModelForm):

class Meta:
model = MyModel
fields = [


{% load static %}

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


#id_my_form_input {
display : none


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;


You are looking for Javascript instead of Django. Since Django does only backend serving and logic, it can't handle any changes happening in the front-end directly. If you don't need to interact with the backend at all during this process, you can simply make javascript (jQuery perhaps) listen for changes in the checkboxes states and if they change, make the form field visible. Form field can be prerendered with Django invisibly (i.e. using <input type="hidden">). Then you can remove the hidden state using Javascript.

If you do need to interact with backend, then you'll want to do basically the same thing with the exception that you render the page with Django, listen for checkbox changes and if the change occurs, you send an AJAX request to a Django view that handles that request and returns the data you need (i.e. from database or some complex calculations that shouldn't be in the front-end). To return the data, you can use Django's JsonResponse.