我正在尝试在Django中创建可折叠表单,一旦单击按钮,该表单就会切换表单。我发现我可以使用jQuery中的.toggle()选项,但我不知道如何将关联的表单与函数
连接http://api.jquery.com/toggle/中的“切换所有段落”示例似乎是我所需要的,但是我不确定如何将其集成。
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$('#toggle').click(function() {
$('form').toggle('slow');
});
</script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Hello world!</title>
</head>
<body>
<h3 class="text-success">Add Sensor</h3>
<br>
<form style="display:none;" method="post">
{% csrf_token %}
<div class="row align-items-center">
<div class="col-sm-8">
<table>
{{ form1.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<button type="button" id="toggle">toggle form</button>
<h3 class = "text-success">Add Sensor View</h3>
<table>
{{ form2.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
</div>
<div>
</form>
我希望仅在按下按钮后才能切换form2
两种形式的定义均类似于以下内容:
class VehicleForm(forms.ModelForm):
class Meta:
model = Vehicle
fields = ['vehicle_id',
'vehicle_name',
'vehicle_modelyear',
'vehicle_version',
'vehicle_file']
widgets = {
'vehicle_id': forms.Textarea(attrs={'rows': 1, 'cols': 15}),
}
答案 0 :(得分:0)
您可以使用style="display:none;"
隐藏表单,并创建一个切换链接,该链接将以缓慢的淡入隐藏或显示表单,如下所示:
<a href="#toggle" id="toggle">toggle form</a><br><br>
<form style="display:none;" method="post">
{% csrf_token %}
<div class="row align-items-center">
<div class="col-sm-8">
<table>
{{ form1.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class = "text-success">Add Sensor View</h3>
<table>
{{ form2.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
</div>
<div>
</form>
在您的JS上:
$('#toggle').click(function() {
$('form').toggle('slow');
});
工作示例:
$('#toggle').click(function() {
$('form').toggle('slow');
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<a href="#toggle" id="toggle">toggle form</a><br><br>
<form style="display:none;" method="post">
{% csrf_token %}
<div class="row align-items-center">
<div class="col-sm-8">
<table>
{{ form1.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
<h3 class = "text-success">Add Sensor View</h3>
<table>
{{ form2.as_table}}
</table>
<div class="mx-sm-2">
<input type="submit" value="Submit">
</div>
<br>
<br>
</div>
<div>
</form>