从复选框操作插入的字段并通过Jquery - Cocoon导轨选择
我无法访问和使用复选框的值,然后为通过Cocoon Gem for Rails动态添加的表单选择字段。我已经阅读了许多SO帖子和官方Cocoon文档,我似乎无法做到。从复选框操作插入的字段并通过Jquery - 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: { ... }
字段被设置为display: none
通过CSS,然后通过JS根据上述值显示或隐藏。这个代码的工作原理(没有cocoon:after-insert
课程的一部分)在一个静态的HTML页面上添加一个项目,而无需像Cocoon一样添加多个项目。
我已经尝试了许多不同方式的代码,基于我在网上找到的不同帖子或网站,但我似乎只能得到第一个测试警报。包括misc_checkbox.find('...')
而不包含$(...)
包装。
我是以这种错误的方式行事还是我的代码错误?预先感谢任何和所有帮助!
更新
当然,只要我后我想通了这个问题。 在[id*="+misc_mortgage"]
丢掉它,我没有正确加载cocoonoptions.js
。要留下这个问题,所以也许它会在未来帮助别人。
所以我的代码是差不多是正确的。有一次,我在看底部通过
<% content_for :javascript do %>
<script type="text/javascript">
</script>
<% end %>
功能改变 $(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]')
到$(misc_checkbox).find('input[type=checkbox][id*="misc_mortgage"]')
和加载JS,一切工作。
伟大的,你找到答案。如果您在需要时添加更新作为未来开发人员的答案,或者如果您希望我可以添加答案来引用您并接受答案,那将会很好。许多开发人员不会阅读没有答案的问题,即使答案在问题本身内:) – Rubioli