Rails 4 - jQuery to hide/show form fields when radio button is moved to true

风流意气都作罢 提交于 2020-01-23 17:33:07

问题


I'm trying to figure out how to use jQuery in my Rails 4 app.

I have a boolean attribute in my table. I ask a question to get a true or false answer using radio buttons in the form.

If the answer is true, my objective is to ask follow up questions which are hidden until true is selected in the form.

I have this form question:

<%= f.input :ethics_relevance, as: :radio_buttons,  :label => 'Is an ethics review relevant?' %>

</div>  

<div id="project_ethics_relevance_content" class="content hidden">

    <div class="row">           
        <%= f.simple_fields_for :ethics do |f| %>
        <%= render 'ethics/ethic_fields', f: f %>
        <% end %>
    </div>

    <div class="row">
        <div class="col-md-6">
            <%= link_to_add_association 'Add an ethics consideration', f, :ethics, partial: 'ethics/ethic_fields' %>
        </div>
    </div>
</div>  

Then in my app/assets/javascripts/projects.js file, I have:

jQuery(document).ready(function() {

   jQuery("#project_ethics_relevance").on('click', function() {
       console.log("here I am ")

           if (jQuery(this)[0].value) {
               jQuery('#project_ethics_relevance_content').removeClass('hidden');
           } else {
               jQuery('#project_ethics_relevance_content').addClass('hidden');
           }
   });

});

I know the attempt above is wrong, I tried to make it based on what I could glean from this post:

Rails 4 form: conditional display of fields based on radio button selection

Can anyone see what I need to do to have a form unhide hidden fields based on radio button form selection?

Chrome inspector on the form shows:

<div class="form-group radio_buttons optional project_ethics_relevance"><label class="radio_buttons optional control-label">Is a research ethics review relevant?</label><span class="radio"><label for="project_ethics_relevance_true"><input class="radio_buttons optional" type="radio" value="true" name="project[ethics_relevance]" id="project_ethics_relevance_true">Yes</label></span><span class="radio"><label for="project_ethics_relevance_false"><input class="radio_buttons optional" readonly="readonly" type="radio" value="false" name="project[ethics_relevance]" id="project_ethics_relevance_false">No</label></span></div>

回答1:


Try this

<script>
jQuery(document).ready(function() {
   jQuery('[name="project[ethics_relevance]"]').on('click', function() {
      if (jQuery(this).val() == 'true' ) {
          jQuery('#project_ethics_relevance_content').removeClass('hidden');
      } else {
          jQuery('#project_ethics_relevance_content').removeClass('hidden').addClass('hidden');
      }
   });

});
</script>


来源:https://stackoverflow.com/questions/38840307/rails-4-jquery-to-hide-show-form-fields-when-radio-button-is-moved-to-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!