简体   繁体   中英

Conditionally show fields on Ruby on Rails form

I have a Ruby on Rails app using Bootstrap for styling. This is a snippet from a form and I want to make a field visible once the non-blank value from the previous field is selected. Thus, once non-blank 'criteria' is selected, I want to make the 'criteria_reason' field visible. How can this code be fixed?

<%= f.select :criteria, ['', 'Yes', 'No', 'Maybe'] %>

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if :criteria == ''}" %>

Thanks!

you can use javascript to make it visible on invisible when you click drop-down.

<script type="text/javascript">
  $(function () {
    $("#category_category_id").change(function () {
        var category = $(this).val();
        if (category != "") {
          $("#category_criteria_reason").show();
        } else {
          $("#category_criteria_reason").hide();
        }
    });

  });
</script>

change category_ with you own form class. Then, you can change you default code into

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

by calling form_for @object do |f| you are passing @object into a ActionView::FormBuilder . In f you can access the related object by calling f.object

so in this case you need to do

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM