How to limit nested form fields using jquery not working

喜欢而已 提交于 2019-12-12 05:49:58

问题


i am following Ryan Bates episode on nested form fields and have added the bit of jquery suggested at the end of part 2. Everything works well(i am able to add fields and remove fields). i now want to limit the number of fields you can add in the form. in my application.js i have

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));
}

as Ryan Bates has written. reading another post i changed the lines to now read:

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));
    }
}

However this does not work, am i doing something wrong here. thanks for the help.

*EDIT
This is the form

<%= 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 %>

The tag field partial

<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>

回答1:


just a small change to calculate the amount of input fields:

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

If you want to check the input contents of a specific div with the id : "controls" (as example) :

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


来源:https://stackoverflow.com/questions/6759605/how-to-limit-nested-form-fields-using-jquery-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!