Ruby on Rails 4.2.
I have a form, where next dropdown is dependent on the previous selection.
The following works (we have a mapping between rails controllers and js files):
(function(App, $, undefined) {
'use strict';
App.AdminReports = function() { # controller name
this.create = function(e) {
$('#quarter').css('display', 'none');
$('#kind_vo').change(function(){
if($('#kind_vo :selected').text() == 'Cele firm' || $('#kind_vo :selected').text() == 'Cele lokalizacji'){
$('#quarter').fadeIn('fast');
}
});
};
};
})(window.App = window.App || {}, jQuery);
But if this faded in field does not pass a rails validation (n my case it is validates :quarter, presence: true
) it disappears again. Is there a way to persist the field longer? I suppose it is happening because of reloading the page on the backend validation fail.
How should I proceed?
May be there is an easy way to persist the faded in field until the controller changes or something like this..
This is how I would approach the problem:
.hidden {
display: none;
}
module FormRowHelper
# A thin wrapper around content_tag to produce an input row.
# @param [Symbol|String] tag_name
# @param [Hash] kwargs - hash of options passed to content_tag
# @option [Boolean] show - adds a hidden class if false
# @yield block to content_tag
# @return [String]
def input_row(tag_name = :div, show: true, **kwargs, &block)
classes = kwargs[:class].try(:split) || ['row']
classes << ['hidden'] unless show
options = kwargs.except(:class).merge(
class: classes.join(' ')
)
content_tag(tag_name, options) do
yield if block_given?
end
end
end
<%= form_for(@model) do |f| %>
<div class="row">
<%= f.select :a do %>
<%= options_for_select(
['Cele firm','Cele lokalizacji', 'Foo', 'Bar']
)
%>
<% end %>
</div>
<%= input_row(
show: ['Cele firm', 'Cele lokalizacji'].include?(@model.a),
id: 'kind_vo') do %>
<%= f.select :b do %>
<%= options_for_select([
['Lisbon', 1, { 'data-size' => '2.8 million' }],
['Madrid', 2, { 'data-size' => '3.2 million' }]
])
%>
<% end %>
<% end %>
<% end %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.