【问题标题】:How to extract input ID in rails to use it in javascript如何在rails中提取输入ID以在javascript中使用它
【发布时间】:2018-03-07 14:43:49
【问题描述】:

我正在尝试根据复选框选中的值显示文本输入字段。 Rails 表单助手使用自动设置的 ID 生成输入。如何在 javascript 中引用它们。

轨道形式的片段

<%= f.check_box_without_bootstrap :standard_product%>
<%= f.label(:standard_product, "Standard product" %>
<%= f.text_field :product_comment%>

Javascript 函数

<script type="text/javascript">
  var checkbox = document.getElementById('????');
  var details_div = checkbox.nextSibling.nextSibling;
  checkbox.onchange = function() {
    if(this.checked) {
      details_div.style['display'] = 'block';
    } else {
      details_div.style['display'] = 'none';
    }
  };
</script>

您能否提出解决方案(这不是为复选框设置 ID)? 谢谢:-)

【问题讨论】:

  • 添加生成的 HTML。
  • 使用类而不是 id 来附加您的事件列表。
  • 检查页面源代码(生成的 html)。你会看到 id。

标签: javascript ruby-on-rails show-hide dom-traversal


【解决方案1】:

Rails check_box 助手定义为:

check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") public

所以在您的代码中,您可以在选项中传递 id

【讨论】:

    【解决方案2】:

    非常感谢。我刚刚从检查员那里复制了生成的 id...

    我想知道如何使用&lt;%= ruby %&gt;&lt;script&gt; 标记中指向由ruby 助手f.check_box 生成的id :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多