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;