从复选框和选择中操作插入的字段 通过 Jquery - Cocoon Rails



我在访问和使用复选框的值时遇到问题,然后为通过 Cocoon Gem for Rails 动态添加的表单选择字段。我已经阅读了许多SO帖子和官方Cocoon文档,但我似乎无法正确理解。

这个想法是,在通过 Cocoon 添加表单后,有一些隐藏字段仅在:checked特定复选框时才会显示,其中一个字段是f.select,并且在选择该值后,将显示或隐藏更多字段。

_mortgage_fields.html.erb

...
<%= f.form_group :misc_mortgage do %>
<%= f.check_box :misc_mortgage, label: "Miscellaneous Mortgage" %>
<% end %>
<%= f.select :misc_mortgage_context, [["Assignment", "Assignment"], ["Subordination", "Subordination"], ["Modification", "Modification"]],
{ label: "Miscellaneous Mortgage Type" }, wrapper: { class: 'mtgHidden' }%>
<%= f.text_field :reference_mortgage, class: 'form-control', wrapper: { class: 'mtgHidden' } %>
<%= f.text_field :subordinated_mortgage, class: 'form-control', wrapper: { class: 'Subordination' } %>
<%= f.text_field :modification_amount, class: 'form-control', wrapper: { class: 'Modification' } %>
...

顶级窗体用<div id="mtgForm">..</div>包装

cocoonoptions.js

$(document.ready(function() {

$('#mtgForm').on('cocoon:after-insert', function(e, misc_checkbox) {
alert('getting there');
$(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]').change(function() {
alert('almost there');
if ($(this).is(':checked'))
alert('there!');
$('.mtgHidden').show();
else
$('.mtgHidden').hide();
});

$(misc_checkbox).find("select[name*='misc_mortgage_context']").change(function() {
var mtg = $(this).val();
if (mtg == "Subordination") {
$('.Subordination').show();
$('.Modification').hide();
}
else if (mtg == "Modification") {
$('.Modification').show();
$('.Subordination').hide();
}
else {
$('.Subordination').hide();
$('.Modification').hide();
}
});
});

wrapper: { ... }字段设置为通过CSSdisplay: none,然后通过JS根据上述值显示或隐藏。同样的代码在静态HTML页面上工作(当然没有cocoon:after-insert部分(,用于添加单个项目,而无需像Cocoon那样一次添加多个项目。

我已经根据我在网上找到的不同帖子或网站尝试了许多不同的代码,但我似乎只能触发第一个测试警报。包括没有$(...)包装器的misc_checkbox.find('...')

我这样做的方式是错误的还是我的代码不正确?提前感谢任何和所有的帮助!

更新

当然,一旦我发布问题,我就想通了。[id*="+misc_mortgage"]中的+把它扔掉了,我没有正确加载cocoonoptions.js。将把这个问题留下来,所以也许它将来帮助将来的某人。

所以我的代码几乎是正确的。一旦我改变了$(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]')$(misc_checkbox).find('input[type=checkbox][id*="misc_mortgage"]')并通过以下方式加载 JS

<% content_for :javascript do %>
<script type="text/javascript">

</script>
<% end %>

视图底部的功能,一切正常。

最新更新