【问题标题】:Rails passing value to hidden field using javascriptRails使用javascript将值传递给隐藏字段
【发布时间】:2021-10-06 22:39:56
【问题描述】:

我有一个结构如下的数组:

<% @locations = [['Town 1',2],['Town 2',2]...] %>

我通过了一个options_for_select 标记,该标记正确地显示了城镇名称并在提交时传递了id,这很棒。但是,我想要做的是传递城镇名称(键?)以及显示在结果页面上。我知道最好的方法是使用带有 javascript 的 hidden_field_tag 来传递值,但我只能传递 id 值,而不是城镇名称值。

表格

<%= form_tag(results_path, method: :post) do %>
  <%= select_tag :location, options_for_select(@locations) %>
  <%= hidden_field_tag(:location_name, value = nil, html_options = {id: 'locationName'}) %>
  <%= submit_tag 'Submit' %>
<% end %>

Javascript

$('#location').change(function(){
  var input = document.getElementById("location");
  var site = document.getElementById("locationName");
  site.value = input.value;
})

【问题讨论】:

    标签: javascript ruby-on-rails


    【解决方案1】:

    当您使用 jquery 时:

    $('#location').change(function(){
      var locationName = $("#location option:selected").text(); # this will return the selected option text e.g. location name
      $("#locationName").val(locationName);
    })
    

    希望它有效!

    【讨论】:

    • 完美!工作一种享受。感谢@Emu 的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2015-09-12
    • 2014-08-14
    相关资源
    最近更新 更多