以Django形式动态显示和隐藏字段
问题描述:
我在Django中有一个表单:
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>
如果类型为1,我希望显示list1元素,隐藏list2,反之亦然如果type为2,则希望它们隐藏并动态显示,而无需重新加载页面或与服务器进行任何交互。
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.
我相信Javascript在这里可能有用,但我不知道。
I believe Javascript could be useful here, but I don't know 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>