jquery - 如何使用 jQuery 将 WTForms TextField 动态添加到 FieldList?

标签 jquery python wtforms flask-wtforms

我想使用 Jquery 添加或删除带有按钮的新 WTForm 输入字段,就像这里一样 http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery/comment-page-1 但使用我的表单字段。

我的表单:

class EditBook(Form):
title = TextField('title', validators = [Required()])
authors = FieldList(TextField())

问题是我不能只附加例如

$(InputsWrapper).append("{{form.authors(size=20)}}");

它只打印这段文字。

最佳答案

您的示例将服务器端生成的文本与您使用 javascript 在浏览器中附加的文本混为一谈。您将无法使用服务器端模板引擎使用的{{ }} 语法。在呈现过程中,这些内容被展开并替换为通过网络传输到客户端的 HTML。相反,您需要构建实际的 DOM 元素,否则这些内置模板函数将生成这些元素。

您实际想要创建的 DOM 元素如下所示:

<input id="authors-0" name="authors-0" type="text" value="Author Guy"></input>
<input id="authors-1" name="authors-1" type="text" value="Other Guy"></input>

然后可以将其编码为WTForms 可以使用的multipart/form-data 流。所以你实际上 jQuery 的东西需要创建一个看起来像这样的字段

$('<input>').attr({
    type: 'text',
    id: 'authors-' + index ,
    name: 'authors-' + index, 
    value: value
}).appendTo('form');

其中 index 是下一个位置索引(这可以存储在包装 ul 中的 data 属性中)和 value 是您要分配给此框的值(如果有)。

此外,要了解 FieldList 呈现的内容,您可以从命令行运行以下代码。它将打印 WTForms 在渲染过程中生成的实际文本。

from wtforms import Form, TextField, FieldList
from webob.multidict import MultiDict

class TestForm(Form):
    authors = FieldList(TextField())

data_in = {'authors': ['Author Guy', 'Other Guy']}
test_form2 = TestForm(data=MultiDict(data_in))
print("HTML Render: %s" % test_form2.authors())

关于jquery - 如何使用 jQuery 将 WTForms TextField 动态添加到 FieldList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915132/

相关文章:

python - 使用列表打开文件?

python - 如何安装 WTForms?尝试导入表单时出现导入错误

python - jinja2.异常.UndefinedError : 'render_field' is undefined

php - 如何设置:hover on a li(A) when hover an other li(B)

jQuery inArray 给出错误的结果

JavaScript keydown 在 Firefox 上不起作用

javascript - WTForms Ajax 验证失败

javascript - Jquery 过滤和显示

Python - 加速寻路

python - 奇怪的重定向位置导致 urllib2 出现代理错误