【发布时间】:2016-10-22 09:12:31
【问题描述】:
请问我有一个关于使用 Django-crispy-form 创建表单的问题。我想要一个包含 2 个字段的表单,并且第一个字段的选择隐藏/显示第二个字段。
- 第一个字段:单选按钮
- 第二个字段:浮点字段
我试过的是:
- 将id分配给单选按钮,将第二个字段放入div中
- 根据分配的 id 单击单选按钮时运行 JS 函数。
- 在JS函数中,获取单选按钮的值
- 根据值,隐藏/显示包含第二个字段的 div。
但在第 3 步,我总是得到“未定义的值”。我想这是因为我无法将 id 分配给选项/选项,而只能分配给没有价值的整个单选按钮。但这只是我的猜测。请参考我的简单代码,如果有人可以帮助我,我将非常感激。
非常感谢!!!
forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineRadios,PrependedAppendedText,Div
class my_form(forms.Form):
# Radio button field
cargo = forms.ChoiceField(label='Cargo on Deck',
choices=[('true','Yes'),
('false','No')],
initial='false')
# the 2nd field
L = forms.DecimalField(label='Length: L [m]')
### Render form
def __init__(self, *args, **kwargs):
super(my_form, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'my_form_id'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', 'Calculate'))
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-4'
self.helper.field_class = 'col-lg-8'
# step 1: Assign id to radio, put 2nd field in a div
self.helper.layout = Layout(
InlineRadios('cargo',id="radio_id"),
Div('L', css_id="div_id"),
)
HTML
<!-- Html -->
{% extends 'home/home_base.html' %}
{% block content %}
<div class="row">
<div class="col-sm-6">
<!-- {% csrf_token %}-->
{% load crispy_forms_tags %}
{% crispy my_form my_form.helper %}
</div>
</div>
<!-- JS -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// step 2: run function when clicking radio button
$(document).ready(function() {
$('#radio_id').on('change',function(){
// step 3: get selected value
var selected_value = $('input[id="radio_id"]:checked').val();
alert(selected_value); // somehow this always gives "undefined value"
// step 4: hide/show dive based on selected_value
if( $(this).val()=="true"){
$("#div_id").hide()
}
else{
$("#div_id").show()
}
});
});
</script>
{% endblock %}
【问题讨论】:
标签: javascript django-crispy-forms