javascript - 在 Django 表单中动态显示和隐藏字段

标签 javascript django forms

我在 Django 中有一个表单:

views.py:

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

主页.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 元素,如果类型为 2,则隐藏 list2 元素,反之亦然。我希望它们动态隐藏和显示,而无需重新加载页面或与服务器进行任何交互。

我相信 Javascript 在这里很有用,但我不知道。

最佳答案

这是对 Andrew 的 Javascript 解决方案的改编,按照您通常期望的方式使用 Django 表单。

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

模板,假设 SearchForm 的一个实例被传递给名为“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>

关于javascript - 在 Django 表单中动态显示和隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136657/

相关文章:

javascript - 尝试删除时删除内部输入的零

python - 将 django-mssql 连接到 mssql 服务器(azure)

python - DRF-Extension缓存忽略查询参数

javascript - 为什么 history.go(-1) 在 IE 和 webkit 浏览器中做不同的事情?

javascript - 如何触发 Span 元素以填充输入字段中输入的值 (Javascript)

python - Django + Angular 在 Heroku 上的部署

javascript - 如何访问 bootstrap-slider 的值(使用 Flask)

php - 如何: Text field only accept certain words

html - 如何自定义同一个类中的元素

javascript - 覆盖小部件的单击事件监听器 - Appcelerator Titanium