Rails - 使字段以表单形式出现,具体取决于select

时间:2012-10-05 13:20:26

标签: jquery ruby-on-rails forms select

当用户从下拉菜单中选择一个选项时,即我们选择"其他"从下拉列表中,下拉菜单下方会显示一个字段"请指定"。我似乎无法让它工作 - "请注明"字段始终显示。我哪里错了?谢谢!

<script>
$(function(){
    $("#pref-select").change(function(){
        if ($("#pref-select").val()=="Other"){
            $("#other-pref").show();
        } else {
            $("#other-pref").hide();
        }
    })
})
</script>

<div class="field">
  <%= f.label :pref %><br />
  <%= f.select :pref, ["", "1", "2", "Other"], {:id => "pref-select"} %>
</div>
<div class="field" id="other-pref">
  <%= f.label :other_preference %><br />
  <%= f.text_area :other_pref %>
</div>

2 个答案:

答案 0 :(得分:7)

你可以这样做: http://jsfiddle.net/vooboo13/RK97r/1/

您为不希望显示css值display:none;

的字段提供

然后使用jQuery监视某个值,如果它是该值则显示它。

HTML:     

选择“菲亚特”,看看魔术发生

<form action="" id="cars">
    <select name="cars" id="car_selector">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="fiat">Fiat</option>
        <option value="audi">Audi</option>
    </select>
    <p>&nbsp;</p>
    <label class="hidden_option">Why would you DO that?</label>
    <input type="text" name="reason" class="hidden_option" />
</form>

JS:

$(document).ready(function(){
    $("#car_selector").change(function(){
        if($("#car_selector").val() == "fiat"){
          $(".hidden_option").fadeIn('fast');   
        }            
    });        
});

CSS:

.hidden_option{
 display: none;   
}

答案 1 :(得分:1)

我从未尝试过,但你听说过dependent-fields-rails宝石吗?