我在Django中有一个表单集。在我已附加了给定编号的选择字段上,我想根据表单集中相应选择的许多表格显示的编号进行显示。 我如何缩写我的代码? 还是有更好的方法来访问表单集中的ID?
$("#id_personenanzahl").change(function() {
if ($("#id_personenanzahl").val() == "0"){
$("#id_form-TOTAL_FORMS").hide("fast");
} else {
$("#id_form-TOTAL_FORMS").hide("fast");
}
if ($("#id_personenanzahl").val() == "1"){
$("#div_id_form-0-vorname").show("fast");
$("#div_id_form-0-nachname").show("fast");
$("#div_id_form-0-geburtsdatum").show("fast");
} else {
$("#div_id_form-0-vorname").hide("fast");
$("#div_id_form-0-nachname").hide("fast");
$("#div_id_form-0-geburtsdatum").hide("fast");
}
if ($("#id_personenanzahl").val() == "2"){
$("#div_id_form-0-vorname").show("fast");
$("#div_id_form-0-nachname").show("fast");
$("#div_id_form-0-geburtsdatum").show("fast");
$("#div_id_form-1-vorname").show("fast");
$("#div_id_form-1-nachname").show("fast");
$("#div_id_form-1-geburtsdatum").show("fast");
} else {
$("#div_id_form-1-vorname").hide("fast");
$("#div_id_form-1-nachname").hide("fast");
$("#div_id_form-1-geburtsdatum").hide("fast");
}
if ($("#id_personenanzahl").val() == "3"){
$("#div_id_form-0-vorname").show("fast");
$("#div_id_form-0-nachname").show("fast");
$("#div_id_form-0-geburtsdatum").show("fast");
$("#div_id_form-1-vorname").show("fast");
$("#div_id_form-1-nachname").show("fast");
$("#div_id_form-1-geburtsdatum").show("fast");
$("#div_id_form-2-vorname").show("fast");
$("#div_id_form-2-nachname").show("fast");
$("#div_id_form-2-geburtsdatum").show("fast");
} else {
$("#div_id_form-2-vorname").hide("fast");
$("#div_id_form-2-nachname").hide("fast");
$("#div_id_form-2-geburtsdatum").hide("fast");
}
})
在代码下方,因为我已将模板集内置到模板中。
{{ formset.management_form }}
{% for form in formset %}
<div class="form-row pt-3" id="personenform">
<div class="form-group col-md-4 mb-0 vorname">
{{ form.vorname|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0 nachname">
{{ form.nachname|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0 geburtsdatum">
{{ form.geburtsdatum|as_crispy_field }}
</div>
</div>
{% endfor %}
<div class="form-actions">
<button type="submit" class="btn btn-success" value="Send">Absenden</button>
</div>
</form>
在此先感谢您的努力,并真诚地属于您。