我试图弄清楚如何使用 Jquery 在我的 Rails 3 应用程序中添加和删除一组字段。我让 jquery 脚本使用纯 html,你可以在这里看到:http: //jsfiddle.net/beehive/ABvFH/1/
但是,我不知道如何将其转换为 Rails 3。更具体地说,我应该在 application.js 文件中用什么替换“formfield”才能使其正常工作?
应用程序.js
$(document).ready(function() {
$(function() {
var x = $('#uploadform');
var i = $('#uploadform ul').size() + 1;
$('#addmore').live('click', function() {
if ($(".item", x).length < 9) {
$('<ul class="item" class="field">formfield ' + i + ' <a href="#" id="remfields">Remove</a></p>').appendTo(x);
i++;
}
return false;
});
$('#remfields').live('click', function() {
if (i > 2) {
$(this).parents('ul').remove();
i--;
}
return false;
});
});
});
form.html.erb
<%= form_for(@upload) do |f| %>
<% if @upload.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@upload.errors.count, "error") %> prohibited this upload from being saved:</h2>
<ul>
<% @upload.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<h2><a href="#" id="addmore">Add More Fields</a></h2>
<div id="uploadform">
<ul class="field">
<li>
<%= f.label :title %><br />
<%= f.text_field :title %>
</li>
<li>
<%= f.label :genre %><br />
<%= f.collection_select :genre, Upload::GENRES, :to_s, :to_s, :include_blank => true %>
</li>
<li>
<%= f.label :category %><br />
<%= f.collection_select :category, Upload::CATEGORIES, :to_s, :to_s, :include_blank => true %>
</li>
<li>
<%= f.label :age %><br />
<%= f.collection_select :age, Upload::AGES, :to_s, :to_s, :include_blank => true %>
</li>
</ul>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>