Rails Forms : change form fields from previously selected fields

早过忘川 提交于 2019-12-08 08:54:16

问题


I have two simple_form fields like this:

<%= f.input :ration_card ,as: :radio_buttons,collection: ["Yes","No"], input_html: {id: "rationcard"} %>
<%= f.input :rationcardNum , label: "Ration Card No." ,input_html: {id: "rationcard_no"} %>  

I want to show the second field only if user selects "Yes" for the first field. My Jquery:

$(function(){
    $("#rationcard").change(function(){
        if ($("#rationcard").val()=="Yes"){
            $("#rationcard_no").show();
        } else {
            $("#rationcard_no").hide();
        }
    })
})  

I can see the js file being included at head of the page.

generated HTML:

<div class="control-group radio_buttons optional family_ration_card">
 <label class="radio_buttons optional control-label" for="rationcard">Ration card</label>
  <div class="controls">
   <label class="radio">
    <input id="rationcard" class="radio_buttons optional" type="radio" value="Yes" name="family[ration_card]" checked="checked">
Yes
   </label>
  <label class="radio">
   <input id="rationcard" class="radio_buttons optional" type="radio" value="No" name="family[ration_card]">
No
  </label>
 </div>
</div>  

<div class="control-group string optional family_rationcardNum">
 <label class="string optional control-label" for="rationcard_no">Ration Card No.</label>
  <div class="controls">
   <input id="rationcard_no" class="string optional" type="text" value="DGFR12" size="50" name="family[rationcardNum]">
  </div>
</div>

But the dynamic fields are not working. What is wrong here?

Or suggest any better way to achieve this.


回答1:


First of all you can't place id on inputs, because you will end up with two inputs with same and jQuery will only find the first one. Secondly, you need to use $(this) inside your handler.

You need sth in line:

<%= f.input :ration_card ,as: :radio_buttons,collection: ["Yes","No"], wrapper_html: {id: "rationcard"} %>
<%= f.input :rationcardNum , label: "Ration Card No." ,wrapper_html: {id: "rationcard_no"} %>

$(function(){
    var toggle_rationcardNum = function(visible) {
        if (visible){
            $("#rationcard_no").show();
        } else {
            $("#rationcard_no").hide();
        }
    }

    $("#rationcard input").change(function(){
        toggle_rationcardNum($(this).val()=="Yes")
    })

    toggle_rationcardNum($("#rationcard input:checked").val()=="Yes")
})();  


来源:https://stackoverflow.com/questions/18961515/rails-forms-change-form-fields-from-previously-selected-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!