0

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>
Hishalv
  • 3,052
  • 3
  • 29
  • 52

1 Answers1

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
    }
}
cillierscharl
  • 7,043
  • 3
  • 29
  • 47
  • thank you. worked out perfectly, however one small issue, when i set the length to 5, and click to add fields it limits me to 3 fields?. Any Idea? – Hishalv Jul 29 '11 at 14:02
  • are there perhaps 2 other type inputs in your container? If so we can refine your selector to exclude them. Perhaps if you show me some of your markup we could assist you further. – cillierscharl Jul 29 '11 at 14:33
  • 1
    perhaps we could try the text input tag in your statement. `$('.fields :text').length < 5;` – cillierscharl Jul 29 '11 at 21:25