使用 ruby“构建”在 Rails 中动态地使用 jQuery
有一个 Rails 应用程序,它有一个表单(新操作),其中包含一个选项值范围从 1 到 5 的选择。当用户选择其中一个选项时,我需要使用 ruby“build”来构建多个对象,具体取决于什么选择的值为。
因此,当用户在选择框中选择 2 时,需要运行以下代码:
@rooms = 2.times { @travel.rooms.build }
另外,当用户将此值从 2 更改为 1 时,代码需要替换为
@rooms = 1.times { @travel.rooms.build }
基本上,我很难找到在 jQuery 中设置该值的方法然后在html中更新它。获取值没有问题,问题是如何在html中动态更改它。
有关如何继续此操作的任何提示?
谢谢, Amund
编辑 - 澄清
我需要在提交表单之前进行此操作。
@rooms = 2.times { @travel.rooms.build }
因此,对上述内容的任何更改都需要在用户位于表单页面时进行。
Got a rails application that has a form (new action) with a select with an options value range from 1 to 5. When the users selects one of the options I need to use ruby "build" to build a number of objects depending on what the select value is.
So when the user selects 2 in the select box the following code needs to run:
@rooms = 2.times { @travel.rooms.build }
Also when the users changes this value from 2 to 1 the code needs to be replaced with
@rooms = 1.times { @travel.rooms.build }
Basically I'm having trouble finding a way to setting the value in jQuery and then updating it in the html. Getting the value is no problem, it's how to dynamically change it in the html that's the issue.
Any tips on how to proceed with this?
Thanks,
Amund
Edit - Clarification
I need this to happen before the form is submitted.
@rooms = 2.times { @travel.rooms.build }
So any changes to the above needs to happen while the user is on the form page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您是否需要 Ruby 帮助或 jQuery 帮助?好吧,无论如何,这里有一些 Ruby。我加入输入验证只是为了更好地衡量:
我不倾向于用 JS 编写解决方案,但一般来说,您可以向选择字段添加一个观察者,然后通过创建 HTML dom 元素来添加字段。假设您已经在页面上构建了其中一种表单,您可能可以采取一些技巧来克隆字段以创建其他字段。另一种方法是始终拥有 5 组字段,并仅显示/隐藏您需要的字段组。祝你好运!
I am not sure if you need Ruby help or jQuery help? Well, here's some Ruby, anyway. I includes the input validation just for good measure:
I'm not inclined to write a solution in JS, but in general, you add an observer to the select field and then add the fields by creating HTML dom elements. Assuming you already have one of the forms built on the page, you can probably do some tricks to clone the fields to create the additional fields. Another way is to always have 5 sets of fields and just show/hide the sets of fields you need. Good luck!
我找到了一种可行的方法,尽管它不漂亮,而且如果用户没有 JS,它也不起作用(在我的例子中,如果用户没有 JS,他们可以 gtfo)。
下面是它工作所需的代码。 (请记住,这是可行的,但我没有采取任何措施使其更简洁或更好)。附:看起来就像是地狱。
然后在模型中我们执行以下操作:
其中 is_wanted 是每个房间表单中的隐藏字段。我确信有更漂亮的方法,但至少它有效。
有什么想法吗?
I've found a way that works, although it's not pretty nor does it work if the user doesn't have JS (In my case if the user don't have JS they can gtfo).
Below is the code needed for it to work. (Keep in mind this works, but I've done nothing to make it more concise or better). ps. It looks like hell.
Then in the model we do:
Where is_wanted is a hidden field in the form for each room. I'm sure there are prettier ways, but at least it works.
Any thoughts?