Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails show fields when radio button is checked

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>

like image 540
Wiggin Avatar asked Sep 17 '12 12:09

Wiggin


People also ask

How to find the selected radio button in HTML?

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 ...

How to select radio buttons using queryselectorall?

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.

How do I know if a radio button is checked?

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:

Is there a way to make multiple radio fields show?

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.


1 Answers

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"));
});
like image 169
egze Avatar answered Sep 28 '22 06:09

egze