Rails表单:从以前选择的字段更改表单字段 [英] Rails Forms : change form fields from previously selected fields

查看:127
本文介绍了Rails表单:从以前选择的字段更改表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 simple_form字段,如下所示:

<%= 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"} %>  

我想只有当用户为第一个字段选择是时才显示第二个字段我的Jquery:

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();
        }
    })
})  

我可以看到js文件被包含在页面的头部。

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

生成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?

或建议任何更好的方法来实现这一目标。

推荐答案

首先你不能把id放在输入上,因为你最终会得到两个相同的输入,jQuery只能找到第一个。
其次,你需要在你的处理程序中使用$(this)。

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.

你需要排队:

<%= 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")
})();  

这篇关于Rails表单:从以前选择的字段更改表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆