Ruby Rails用JavaScript将字段添加到表单

jpfvwuh4  于 2023-04-29  发布在  Ruby
关注(0)|答案(2)|浏览(113)

我使用Ruby on Rails和JavaScript。我想创建一个表单,其中一个字段可以有多个“对象”。在我的示例中,员工可以添加多个编队。
只是让你知道,我不太懂JavaScript,我不是Web语言的Maven。所以请在下面的代码中解释一下我的问题。
这是我的employ_form中的代码。html.erb

<div id="formationSet" class="form-group row">
</div>
<a href="javascript:" id="addNewFormation">Add Formations</a>

这是我在员工培训中的代码。js

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"><input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>    </div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

这是我的应用程序代码。js

//= require employeFormation

我实际上想要的是,当我单击addFormation时,它在另一个下面添加一个字段,我可以删除它,并在创建新员工时添加到我的对象中
谢谢你的回答。
编辑:更正了代码中的一些错别字(感谢KKK)。但它仍然不起作用

eeq64g8w

eeq64g8w1#

代码中的问题是在javascript中引用了错误的id。在HTML中,id是FormationSet,而在JavaScript中,您尝试将form追加到formationSet div中。更改HTML中的id,它可以正常工作。

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"><input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>    </div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formationSet" class="form-group row">
</div>
<a href="javascript:" id="addNewFormation">Add Formations</a>
tyky79it

tyky79it2#

在Ruby4上面。0 aparently $(文档)。不要像以前那样得到通知。所以我不得不把它改成这样:

var ready = function() {
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"> <%=     f.label :email %> \n <%= f.text_field :email %>' +

        '<button class="removeNewFormation" type="button">remove</button></div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
};

$(document).ready(ready);
$(document).on('page:change', ready);

相关问题