show rest of a form if a checkbox is ckecked in ruby on rails

suely picture suely · Apr 25, 2012 · Viewed 10.3k times · Source

I need to ask to my user if will pay a service with credit card...if it checked the option pay_with_card? it must show the rest of the form, that ask for other data like card number, mail, etc. if the user don't checked it, it must show a message, the question is...how can I do this? thanks in advance

<%= form_for(@product) do |f| %>
  <%= f.label :pay_with_card? %>
  <%= f.check_box :pay_with_card,{}, "Yes", "No"%>
  <div>
    <%= f.label :card_number %> <%= f.text_field :card_number %>
  </div>  
  <div>
    <%= f.label :mail %> <%= f.text_field :mail %>
  </div>
<% end %>

Answer

Unixmonkey picture Unixmonkey · Apr 25, 2012

Make the card number/mail details div style="display:none;", then add some javascript to the checkbox to change it to display:block;

Something like this:

<%= form_for(@product) do |f| %>
  <%= f.label :pay_with_card? %>
  <%= f.check_box :pay_with_card,{}, "Yes", "No"%>
  <div id="card_details" style="display:none;">
    <%= f.label :card_number %> <%= f.text_field :card_number %>
    <%= f.label :mail %> <%= f.text_field :mail %>
  </div>
<% end %>
<script type="text/javascript">
  var checkbox = document.getElementById('product_pay_with_card');
  var details_div = document.getElementById('card_details');
  checkbox.onchange = function() {
     if(this.checked) {
       details_div.style['display'] = 'block';
     } else {
       details_div.style['display'] = 'none';
     }
  };
</script>