如果选中复选框,则会显示div

时间:2015-08-06 11:07:58

标签: jquery ruby-on-rails

我是rails / Jquery的新手,我遇到了问题。我的目标是:如果选中checkbox(credit_card_fields),则会显示div (credit_card_fields)

这是我的剧本:

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

形式:

<%= form_for(:estudante, :url => {:action => 'create'}) do |f| %>

  <%= f.label :pay_with_card? %>
  <%= f.check_box :pay_with_card,{}, "Yes", "No"%>
  <div id="credit_card_fields" style="display:none;">
    <%= f.label :card_number %> <%= f.text_field :card_number %>
    <%= f.label :mail %> <%= f.text_field :mail %>
  </div>

<% end %>

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$("#pay_with_card").change(function(){
  $("#credit_card_fields").toggle($(this).is(":checked"));
});
&#13;
<!-- THIS HTML IS FOR DEMO PURPOSES ONLY! -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>pay_with_card?</label>
<input type="checkbox" name="estudante[pay_with_card]" id="pay_with_card" checked="checked">
<div id="credit_card_fields">
  <label>card_number</label>
  <input type="text" name="estudante[card_number]">
  <label>mail</label>
  <input type="text" name="estudante[mail]">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以将参数传递给.toggle()方法:

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

答案 2 :(得分:0)

你忘记了jQuery ready function。试试这个:

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