我的表格定义为:
class testForm(forms.Form):
book = forms.CharField(label='Book:', widget=forms.TextInput())
我试图在表单中添加动态字段。这意味着文本框旁边有一个按钮,如果单击该按钮,则原始文本框下会出现一个新文本框,此表单只有一个表单。
在我的模板中:
<table>
{{form.as_table}}
<table class = 'request'>
{{form.as_table}}
{# <input type="button" onclick="addTextBox()"/>#}
{# <span id="response"></span>#}
</table>
<br>
<input type="submit" value="Submit">
</table>
我不想更改我的模板,因此我尝试使用js来完成它。
var countBox = 1;
var boxName = 0;
function addTextBox(){
boxName = "textBox"+countBox;
document.getElementById('response').innerHTML+='<br/><input type="text"
id="'+boxName+'" value="'+boxName+'" " /><br/>';
countBox += 1;
}
但它没有做我想要的,有没有人有想法?
答案 0 :(得分:0)
我不知道这对您是否合适,但您可以尝试使用包含一个表单的页面来添加所有新书并显示其他表单。 基本上,当您通过表单添加新书时,它将使用ajax刷新页面,表单将不会出现在任何地方,您的书将在数据库中,因此将显示在同一页面中。
这是基本代码: views.py:
def all(request):
obj = Books.objects.all()
...
模板:
<div id='books'>
{% for o in objs %}
{{ o }}
{% endfor %}
<form method='POST' action='#' enctype='multipart/form-data'>
{% csrf_token %}
// your form
<table>
{{form.as_table}}
<table class = 'request'>
{{form.as_table}}
{# <input type="button" onclick="addTextBox()"/>#}
{# <span id="response"></span>#}
</table>
<br>
// end of your form
<input type="submit" value="Submit">
</table>
<input class="ui button" type='submit' value='Add Skill' />
</form>
</div>
<script type="text/javascript">
$("#addform").submit(function(e) {
var url = $(this).attr('action');
var formData = new FormData(this);
$.ajax({
type: "POST",
url: url,
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$("#books").load("# #books");
}
});
e.preventDefault();
});
</script>
如果我遇到同样的问题,我会继续这样做,但这当然是你的决定。