Rails shows fields when radio button is set

I am developing a Rails application and I need to show / hide a specific field when I click on the switch.

I am using javascript, but I cannot get it to work.

Any tips on how to solve this?

Button radio code

<%= radio_button 'relat', 'atu', 'yes' %>   ATU
<%= radio_button 'relat', 'atu', 'no' %>    No ATU

The field that will be displayed with the first button

<div id="esatu" style="display:none">
<p>
    <label for="relat_tipus_atu">
    Tipus ATU
    </label>
    <%= select_tag :tipus_id, "<option value=''></option>".html_safe + options_from_collection_for_select(@tipus, :id, :codi) %>
</p>

+5
source share
1 answer

First, give your radio books some class names, so you can use them with javascript more easily.

<%= radio_button 'relat', 'atu', 'yes', {:class => "relat__atu relat__atu_yes"} %>   ATU
<%= radio_button 'relat', 'atu', 'no', {:class => "relat__atu relat__atu_no"} %>    No ATU

Now you attach the event handler to the change event. And switch the display of your other item, depending on whether the Yes button is turned on.

$(".relat__atu").on("change", function(){
  $("#esatu").toggle($(this).hasClass("relat__atu_yes"));
});
+10
source

All Articles