如何使用jQuery限制嵌套表单字段不起作用 [英] How to limit nested form fields using jquery not working

查看:101
本文介绍了如何使用jQuery限制嵌套表单字段不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正如瑞安·贝茨(Ryan Bates)所写.阅读另一篇文章后,我将行改为现在:

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
这是表格

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

推荐答案

更改一下即可计算出输入字段的数量:

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

如果要检查id为"controls"的特定div的输入内容(例如):

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

这篇关于如何使用jQuery限制嵌套表单字段不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆