使用变形制作表单,并希望根据用户所做的选择更改 pageShema 类。 前任。如果他从 selectwidget 选择选项 1,则向他显示一组字段,如果是其他选择 - 另一个。 这个怎么做?
请您参考如下方法:
您可以使用 jquery 并使用“名称”属性进行选择。 此外,您可以使用 jquery 的“parent()”函数来获取您有兴趣显示/隐藏的输入容器。
例如,在您的架构中执行如下操作:
# This is the "<select>"
choices = (('yes','Yes'),
('no', 'No'))
bar = colander.SchemaNode(colander.String(),
widget=deform.widget.SelectWidget(values=choices))
# This is the input that should appear only when the "yes" value is selected
foo = colander.SchemaNode(colander.String())
然后,在您的模板中,添加如下内容:
<script>
$( document ).ready(function() {
// ensure that the "foo" input starts hidden
var target = $("input[name=foo]").parent().parent();
target.hide();
$("select[name=bar]").on('change', function(){
var valueSelected = this.value;
if (valueSelected == "yes") {
target.show();
} else {
target.hide();
}
});
});
</script>
