请问我有关于使用Django-crispy-form创建表单的问题。我希望有一个包含2个字段的表单,第一个字段的选择隐藏/显示第二个字段。
我尝试的是:
但在第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 %}
答案 0 :(得分:0)
对于HTML文件中的第3步,请尝试使用:
$('input[name="cargo"]:checked').val();