【问题标题】:Rails - changing whether a field is displayed or not dependent on select - not quite workingRails - 改变是否显示字段取决于选择 - 不太有效
【发布时间】:2012-10-05 13:57:00
【问题描述】:

我有一个表单,如果用户从下拉列表中选择“其他”,下面会出现一个字段,上面写着“其他 - 请指定”。但是,它并不完全有效。如果我为“请指定”字段设置 display:none,那么当保存表单并且用户返回编辑它时,他们看到的只是选择框,而不是“请指定”字段。

我知道为什么会发生这种情况 - 这是因为 jQuery 正在等待用户在 show 事件触发之前更改选择框。

但是,如果我从 CSS 中删除 display:none,那么当用户首次显示表单时,他们会看到选择框和“请指定”字段,无论选择框中显示什么。我能做些什么来解决这个问题?我也可以在页面加载时执行代码的“if”块,但不知道该怎么做?谢谢!!

<script>
$(function(){
    $("#pref_select").change(function(){
        if ($("#pref_select").val()=="Other"){
            $("#other-pref").show(500);
        } 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 - please specify" %><br />
  <%= f.text_area :other_pref %>
</div>

【问题讨论】:

  • 您可以在页面加载时触发更改...通过将 .change() 添加到语句的末尾...然后它会在每次加载页面时检查该值
  • 对不起,我对 JS 还不是很了解——我需要在哪里放置额外的 .change()?谢谢
  • $("#pref_select").change(function(){ if ($("#pref_select").val()=="Other"){ $("#other-pref").show(500); } else { $("#other-pref").hide(); } }).change() //
  • 就是这样,非常感谢!随意把它作​​为一个答案,所以我可以接受:)
  • 欢迎您。很高兴它帮助你得到你想要的:)

标签: jquery ruby-on-rails forms select


【解决方案1】:

如果要触发页面加载检查,请触发更改事件。您绑定了更改事件,但您的检查只有在触发后才会发生。因此,为了获得您想要的效果,您需要在页面加载时触发 change()

$("#pref_select").change(function() {
    if ($("#pref_select").val() == "Other") {
        $("#other-pref").show(500);
    } else {
        $("#other-pref").hide();
    }
}).change()​ // <-- this triggers the change event

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多