使用Jade/Jquery更改表单
Change form using Jade/Jquery
我正在尝试让一个表单更改其选项以响应另一个事件。蛋糕需要在.sweet更改时更新,但蛋糕最初是通过res.render的,我不知道如何在不重新加载页面的情况下更改它。我只是这方面最好的ajax解决方案。
应用程序:
res.render('index', {cakes: json_object});
正文:
form(name="myform")
div.input
each item in cakes.topping
input(type="checkbox", name=item.color)
| #{item.color}
尝试换蛋糕:
磁头:
$(document).ready(function(){
//requesting new Object
$(".sweet").change(function () {
socket.emit('choose', {sweet: $("#cho_swe").val()});
});
//getting new object
socket.on('set_sweet', function(object){
-- object is a new JSON which needs to replace cakes in the form below
});
});
如何将我的新对象转换为可以在循环中使用的格式?
注意:将把jade称为pug,以纪念他们被迫更换的品牌
当您在应用程序文件中呈现Pug时,Pug会在后端进行编译。然而,您正在与渲染文件并行发送额外的变量,pug对此没有任何作用域。
当您渲染它时,您将无法访问Pug函数
每个
item in cakes.topping
现在是
<input 1/>
<input 2/>
etc...
在这一点上,Pug已经完成了它的工作,现在这是一个前端问题。你不能使用pug的循环函数,你需要依靠前端框架或库来使内容动态。
有几种方法可以处理这个问题,但我看到你正在使用jquery,所以我们可以走那条路:
接收套接字广播时重新填充元素:
$(document).ready(function(){
//get the form element
$form = $('form[name="myform"]').empty();
//requesting new Object
$(".sweet").change(function () {
socket.emit('choose', {sweet: $("#cho_swe").val()});
});
//getting new object
socket.on('set_sweet', function(object){
//
// clear the current form and add the new html
// if you know most of the html before hand and just have a few dynamic
// fields consider having them in the pug template with
// display: none;
//
// dynamically add new elements without needing a page reload
object.forEach(function(val, key) {
$form.append('<div>'
+' <input type="checkbox" onclick="someClickHandler()" name="' + val + '"/>'
+' <div>' + val + '</div>'
+' </div>');
});
});
});
如果你发现自己需要做很多动态内容,可以考虑使用angularjs这样的框架。
上述有角度的解决方案类似于:
form(name="myform")
div.input
div(ng-repeat="item in items")
input(type="checkbox", name=item.color)
| #{item.color}
socket.on('set_sweet', function(object){
$scope.items = object;
});
总之,pug将在后端编译一个页面,其中包含所有可用的内容、变量和所有内容,但一旦它被传递和呈现,你就要在前端让内容变得动态。
相关文章:
- jQuery表单添加不适用于下拉列表
- 同时打印并提交表单-jQuery.Print
- 如何不清除表单jQuery中禁用的输入
- 如何检查输入中的值以及值是否存在提交表单?jquery.
- 登录表单 jQuery 插件无法按预期工作
- 谷歌电子表格网站表单jQuery脚本阻止发送
- 如何做不成功提交表单jquery
- 将表单和输入附加到表单jQuery Mobile
- 在我的切换表单jquery脚本中出现问题
- 使用动态表单 jquery 创建多维数组
- 使用一个类提交多个表单(jquery, rails)
- 有一个按钮打开右边的表单JQuery
- 取消按钮php表单jquery
- 按钮必须按一个特定的顺序发送表单- jquery
- 产品验证表单jquery
- rails嵌套表单jquery图像预览
- 获取表单(Jquery与Javascript)
- 将类型文件的输入附加到表单jquery中
- 如何从理想表单jQuery中删除验证规则
- Ruby on rails -加载更多按钮与kaminari和搜索表单.Jquery的问题