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

10,509

Solution 1

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>

Solution 2

How about using jQuery?

First, wrap your credit card fields in a div with class credit_card_fields and than add this JS code to your page:

$("input[type='checkbox']#pay_with_card").on('change', function(){
  $('.credit_card_fields').toggle();
});

Solution 3

You can use JS for it or move pay_with_card out of form like:

<%= link_to 'pay with card', your_current_path(:pay_with_card => 1) %>
<%= form_for(...) do |f| %>
  <% if params[:pay_with_card] %>
    <%= # fields for card %>
  <% end %> 
<% end %>

Solution 4

You can do it through jQuery, for example:

$ ->
  $('select#pay_with_card').change ->
    if $(this).val() == 'yes'
      $('.card_block').slideDown('fast')
    else
      $('.card_block').slideUp('fast')

assumed that part of the form with payment card is included in the div with .card_block class

Share:
10,509
suely
Author by

suely

Updated on June 27, 2022

Comments

  • suely
    suely about 2 years

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