How to show and hide form fields based on selection from a dropdown menu in Django

I have a question about how to conditionally hide or show a field based on choosing its parent field in Django.

** UPDATE: I can implement this function of this function by defining a function in JavaScript that has been tested with some simple HTML code. However, since my input table is created by Django, can someone tell me what to call this function in Django 'onchange'? **

FINAL UPDATE: I think it is easier to use jQuery for this. jQuery: Conditional display of an item based on a dropdown list

JavaScript: Explanation: 1. Before making any selection, you can only see the drop-down menu "Application Method", 2. If you select "Air Spray" from the parent field, then the "Antenna Size" drop-down menu, 3. If you select "Ground Spray" from the parent block, then another drop-down list "Type of spray for soil" requires input

<script type="text/javascript">
function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';

if ( txt.match(id1) ) {document.getElementById(id1).style.display = 'block';}
if ( txt.match(id2) ) {document.getElementById(id2).style.display = 'block';}
</script>

<table>
<tbody align="center">
<tr><th>Application method:</th>
<td><select onchange="display(this,'A','B')" name="method" id="id_method">
<option value="">Pick a method</option>
<option value="A">Aerial Spray</option>
<option value="B">Ground Spray</option>
</select></td></tr></tbody>

<tbody id="A" align="center" style="display: none;">
<tr><th><label for="id_aerial_size_dist">Aerial Size Dist:</label></th><td><select select name="aerial_size_dist" id="id_aerial_size_dist">
<option value="" selected="selected">Pick first</option>
<option value="A1">Very Fine to Fine</option>
<option value="A2">Fine to Medium (EFED Default)</option>
</select></td></tr>
</tr>
</tbody>

<tbody id="B" align="center" style="display: none;">
<tr><th><label for="id_spray_type">Ground spray type:</label></th><td><select name="spray_type" id="id_spray_type">
<option value="B1" selected="selected">Low Boom Ground Sprayer (20 Inches or Less)</option>
<option value="B2">High Boom Ground Sprayer (20 to 50 Inches: EFED Default)</option>
</select></td></tr></tbody></table>

Django code that now doesn't work. He needs help about all of the specific 'display' functions.

updat, after adding mark_safe the code works.

class GENEECInp(forms.Form):
    application_method = forms.ChoiceField(required=True, choices=applicationmethod_CHOICES, initial='Aerial Spray',
                                           widget=forms.Select(attrs={'onchange':mark_safe("display(this,'A','B','C','D');")})
+3
source share
1 answer

You will need some kind of custom javascript to hide or show the corresponding field. Do you have javascript in this widget?

0
source

All Articles