Show and hide dynamic fields in Django form

I have a form in Django:

views.py:

class SearchForm(forms.Form): type = forms.ChoiceField(choices = ...) list1 = forms.ModelMultipleChoiceField(...) list2 = forms.ModelMultipleChoiceField(...) 

home.htm:

 <td valign='top'>{{ form.type }}</td> <td valign='top'>{{ form.list1 }}</td> <td valign='top'>{{ form.list2 }}</td> <td valign='top'><input type="submit" value="Find" /></td> 

I want list1 to be displayed and list2 to hide if the type is 1, and vice versa if the type is 2. I want them to be hidden and displayed dynamically without reloading the page or any interaction with the server.

I believe Javascript can be useful here, but I don't know that.

+4
source share
2 answers

Try it...

 <script>function Hide() { if(document.getElementById('mainselect').options[document.getElementById('mainselect').selectedIndex].value == "1") { document.getElementById('a').style.display = 'none'; document.getElementById('b').style.display = ''; }else { document.getElementById('a').style.display = ''; document.getElementById('b').style.display = 'none' } } </script> <td valign='top'><select id="mainselect" onchange="Hide()"><option value="1">1</option><option value="2">2</option></select></td> <td valign='top' id='a'>{{ form.list1 }}</td> <td valign='top' id='b'>{{ form.list2 }}</td> <td valign='top'><input type="submit" value="Find" /></td> 
+3
source

This is an adaptation of the Andrew Javascript solution using Django forms, as you usually expected.

Form in Django / Python:

 class SearchForm(forms.Form): type = forms.ChoiceField(choices = ((1, 'One'), (2, 'Two'))) # Use any form fields you need, CharField for simplicity reasons list1 = forms.CharField() list2 = forms.CharField() 

A template assuming that the SearchForm instance SearchForm passed to the template context named "form":

 <script> function Hide() { if(document.getElementById('id_type').options[document.getElementById('id_type').selectedIndex].value == "1") { document.getElementById('id_list1').style.display = 'none'; document.getElementById('id_list2').style.display = ''; } else { document.getElementById('id_list1').style.display = ''; document.getElementById('id_list2').style.display = 'none'; } } window.onload = function() { document.getElementById('id_type').onchange = Hide; }; </script> <div> {{ form.type.label_tag }}{{ form.type }} </div> <div> {{ form.list1.label_tag }}{{ form.list1 }} </div> <div> {{ form.list2.label_tag }}{{ form.list2 }} </div> 
+4
source

All Articles