user3018934
user3018934

Reputation: 121

Django - How to display fields based on the option selected in a list box?

Below is the form. I want to display the web check boxes (days) only when the user selects weekly option. Should this logic be done be done in the view, template or form? Can someone point me to an example?

class bugtoolform(ModelForm):
    F_Choices = (
        ('DAILY','DAILY'),
        ('HOURLY','HOURLY'),
        ('WEEKLY','WEEKLY'),        
        )
    frequency = forms.TypedChoiceField(choices = F_Choices)

    DAY_CHOICES = (
        ('1', 'MONDAY'),
        ('2', 'TUESDAY'),
        ('3', 'WEDNESDAY'),
        ('4', 'THURSDAY'),
        ('5', 'FRIDAY'),
        ('6', 'SATURDAY'),
        ('7', 'SUNDAY'),
        )   

    days = forms.MultipleChoiceField(required=False,
        widget=forms.CheckboxSelectMultiple, choices=DAY_CHOICES)
    #</br>

    class Meta:
        model = bugtool     
        fields = ['frequency','days']

Upvotes: 2

Views: 3773

Answers (2)

user3018934
user3018934

Reputation: 121

I was able to get jquery working using the id field however im not sure how to use it with django forms. Not able to retrieve the form field value accordingly in the script. Any help will be appreciated.

Below is my template

<html>
<head>
<h1>Tool !!!!</h1>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#{{form.frequency}}').change(function(){
if( $('#{{form.frequency.value}} == 'WEEKLY' ) {
     $('#showthis').show();
} else {
     $('#showthis').hide();
}
});
});
</script>

<div id='showthis'>test test</div>
</head>
<body> 
<form action="/tool/" method="post">
{% csrf_token %}
Frequency {{form.frequency}}
</br>
</br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
{{form.days.as_hidden}}

</br>        
    <input type="submit" value="Submit">
</form>
</body>
</html>

Upvotes: 1

bogeylicious
bogeylicious

Reputation: 5160

This is something that you would want to do on the front-end with javascript.

Here is the general process at a high level:

  • Hide the days checkboxes by default with CSS (display: none) or javascript
  • Listen to the 'change' event on the frequency field
  • When the 'change' event fires, evaluate the value of the frequency field and show the days checkboxes if weekly is selected using CSS (display: block) or javascript

Upvotes: 2

Related Questions