0

我正在关注关于嵌套表单字段的 Ryan Bates 剧集,并在第 2 部分末尾添加了一些 jquery 建议。一切正常(我能够添加字段和删除字段)。我现在想限制您可以在表单中添加的字段数量。在我的 application.js 我有

function add_fields(link, association, content) {
        var new_id = new Date().getTime();
        var regexp = new RegExp("new_" + association, "g")
        $(link).parent().before(content.replace(regexp, new_id));
}

正如瑞安贝茨所写。阅读另一篇文章我将这些行更改为现在阅读:

function add_fields(link, association, content) {
    if($(".fields input").length < 5) {
        var new_id = new Date().getTime();
        var regexp = new RegExp("new_" + association, "g")
        $(link).parent().before(content.replace(regexp, new_id));
    }
}

但是这不起作用,我在这里做错了什么。谢谢您的帮助。

*编辑
这是表格

<%= form_for @question, :url => { :controller => "questions", :action => "create" } do |f| %>
    <%= f.label(:name, "Request Question:") %>&nbsp;&nbsp;
    <%= f.text_field(:name, :size => 72, :maxlength => 120, :id => "name") %><br />
    <fieldset>
        <legend><b>Tags</b></legend>
        <%= f.fields_for :tags, :url => { :controller => "tags", :action => "create" } do |builder| %>
            <%= render "tag_fields", :f => builder %>
        <% end %>
        <p><%= link_to_add_fields "Add new keyword", f, :tags %></p>
    </fieldset>
<% end %>

标签字段部分

<p class="fields">
    <%= f.label(:keyword, "Keywords:") %>&nbsp;&nbsp;
    <%= f.text_field(:keyword, :size => 20, :maxlength => 25, :id => "keyword") %>
    <%= link_to_remove_fields "remove", f %>
</p>
4

1 回答 1

1

计算输入字段数量的小改动:

function add_fields(link, association, content) {
    if($(":input").length < 5) {
       // logic to add items
    }
}

如果您想使用 id 检查特定 div 的输入内容:“controls”(例如):

function add_fields(link, association, content) {
    if($("#controls :input").length < 5) {
       // logic to add items
    }
}
于 2011-07-29T12:30:35.850 回答