I'm developing a Rails application and I need to show/hide a certain field when a radio button is clicked.
I'm using javascript but I can't seem to get it working.
Any tips on how to solve that?
Radio Button code
<%= radio_button 'relat', 'atu', 'yes' %> ATU
<%= radio_button 'relat', 'atu', 'no' %> No ATU
Field that's going to show when the first button is checked
<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>
To find the selected radio button, you use these steps: 1 Select radio buttons by using DOM methods such as querySelectorAll () method. 2 Get the checked property of the radio button. If the checked property is true, the radio button is checked; otherwise,... More ...
Select radio buttons by using a DOM method such as querySelectorAll () method. Get the checked property of the radio button. If the checked property is true, the radio button is checked; otherwise, it is not.
Get the checked property of the radio button. If the checked property is true, the radio button is checked; otherwise, it is not. To know which radio button is checked, you use the value attribute. For example:
For making extra fields show, it could be achieved by setting the Visible property of the data card of the fields to: But for the the multiple radio selection part, I think this cannot be achieved so far. The only similar control you could use so far is Combo box control.
First, give your radio buttons 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 an event handler to the change event. And toggle the display of your other element, depending if the radio button is the "yes" button.
$(".relat__atu").on("change", function(){
$("#esatu").toggle($(this).hasClass("relat__atu_yes"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With