0

感谢您对此的帮助。目标是将下拉列表中选定选项的一些数据作为值放入隐藏字段中。我已经用 HTML 测试了 Rails 之外的基本思想(请参阅此处修改过的小提琴:http: //jsfiddle.net/e6zZB/1/)并且它有效。只有当我转到 Rails 隐藏字段时,该值似乎没有改变。我的测试方法是在下拉列表中选择一个选项,然后检查源以查看值是否已更新(但不确定这是否是一个好方法!)仅供参考,这是 Rails 2(它是一个较旧的项目)。

jQuery

    $(document).ready(function(){
    $("#startdrop").change(function () {
          var startidval = this.options[this.selectedIndex];
          $("#start-masterlocation-id-field").val($(startidval).data("data-masterlocation-id"));
        });
    });

视图中的 Rails 下拉菜单

    <select id="startdrop" name="startthere">
<% for location in @itinerary.locations %>
<option data-masterlocation-name="<%= location.masterlocation.name %>" data-masterlocation-id="<%= location.masterlocation.id %>" value="<%= location.masterlocation.street_address %>, <%= location.masterlocation.city %>, <%= location.masterlocation.state %>, <%= location.masterlocation.zip %>"><%= location.masterlocation.name %></option>
<% end %>
</select>

视图中的 Rails 隐藏字段

    <%= hidden_field :newsavedmap, :start_masterlocation_id, :id => "start-masterlocation-id-field" %>

最终作品

    $("#startdrop").change(function () {
        var startidval = $(this).find('option:selected').attr('data-masterlocation-id');
        $("#start-masterlocation-id-field").val(startidval);
});
4

0 回答 0