rails 表单动态添加字段 [英] rails form add fields dynamically

查看:51
本文介绍了rails 表单动态添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一组字段设置为按需动态显示.在模型中,我有字段:

I'm trying to set a set of fields to be dynamically displayed on demand. In the model, I've the fields:

attr_accessible ... :instruct1, :instruct2, ... :instruct30

我希望表单只显示instruct1,并带有一个按钮来添加1个字段,直到instruct30被点击,还有一个按钮可以删除一个直到instruct 1被点击.一切都应该在没有刷新页面的情况下发生,我认为这会包含一些 AJAX 的使用,但我找不到任何类似的东西.

I would like the form to display just instruct1 with a button to add 1 more field until instruct30 is hit and a button to remove one until instruct 1 is hit. All should happen without refreshing page which i think would include some use of AJAX but I couldn't find anything that is similar.

我搜索了类似的东西,但只能提出嵌套表单,这不是我要找的,因为我的模型是固定的.

I've searched for something similar but only able to come up with nested form which is not what im looking for as my model is fixed.

推荐答案

您的大部分工作都将在客户端进行.

The majority of your work is going to be on the client side.

要动态添加和删除表单字段,您必须使用 javascript.查看 Rails 为第一个字段生成的 HTML,复制它并使用例如 jQuery 添加其他字段.

To add and remove form fields dynamically, you have to use javascript. Check out the HTML that Rails generates for the first field, replicate that and add the additional fields using for example jQuery.

一个粗略的例子:

$("#button").click(function() {
  $("#theForm")
    .append('<input id="instruct2" name="object[instruct2]" type="text">');
});

您必须跟踪您添加或删除了多少字段.

You'd have to keep track of how many fields you've added or removed.

这篇关于rails 表单动态添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆