Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - Show and hide dynamically 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 the list1 element to be shown and the list2 to be hide if type is 1 and vice versa in case type is 2. I want them to be hide and shown dynamically without reloading the page or any interaction with the server.

I believe Javascript could be useful here, but I don't know it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an adaption of Andrew's Javascript solution, using Django forms the way you'd usually expect.

The 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()

The template, assuming an instance of SearchForm got passed to the template context with the name '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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...