Mel Mel - 3 months ago 12
jQuery Question

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

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>

Answer

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>