gpt4 book ai didi

jquery - CoffeeScript 在更改和加载时动态选择表单字段

转载 作者:行者123 更新时间:2023-12-03 23:03:31 25 4
gpt4 key购买 nike

我有一个 Rails 应用程序,我试图根据表单中选择的区域来选择设施列表。到目前为止,我已经实现了 group_collection_select 以及一些 CoffeeScript 来执行此操作。

它在创建新记录和选择区域时起作用。行为是仅显示为所选区域列出的设施。不起作用的是,在编辑记录时,选择设施会显示按区域分组的所有设施,而不是将设施限制在所选区域。

如果我选择另一个区域,然后选择原始原因,则会显示正确的设施列表。

我想了解如何重构 CoffeeScript,以便在编辑记录时在页面加载(编辑时)和更改时触发函数。

最后,在某些情况下,transfer_from_id 设置为 nil/blank,并且我们使用名为transfer_from_other 的文本字段。目前,如果我不选择设施并填写transfer_from_other,因为CoffeeScript在transfer_from_id中加载设施,它将通过范围内的第一个设施设置transfer_from_id。我想将其设置为如果未选择任何设施,transfer_from_id 为零,因此我可以使用transfer_from_other。

这是我的代码:

calls.js.coffee

jQuery ->
facilities = $('#call_transfer_from_id').html()

$('#call_region_id').change ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()

if options
$('#call_transfer_from_id').html(options)
else
$('#call_transfer_from_id').empty()

区域.rb

has_many :facilities

设施.rb

attr_accessible :region_id
belongs_to :region

_form.html.erb 摘录

      <%= f.label :region %>
<%= f.collection_select(:region_id, Region.all, :id, :area, {:include_blank => true}, {:class => 'select', required: true}) %>
<%= f.label :Transfer_From %>
<%= f.grouped_collection_select :transfer_from_id, Region.order(:area), :active_facilities, :area, :id, :facility_name, {include_blank: true}, class: 'select' %>
<%= f.label :Transfer_From_Other%>
<%= f.text_field :transfer_from_other %>

如果我的问题和示例不清楚,请告诉我,我很乐意进行编辑。

最佳答案

关于在页面加载和选择更改时更新选择,除非我遗漏了某些内容,否则仅仅将选择更新部分分解为它自己的函数,然后在页面加载时调用一次,这还不够吗?然后每次选择都会发生变化?

jQuery ->
facilities = $('#call_transfer_from_id').html()

update_facilities = ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()

if options
$('#call_transfer_from_id').html(options)
else
$('#call_transfer_from_id').empty()

$('#call_region_id').change ->
update_facilities()

update_facilities()

关于第二部分,每次更新#call_transfer_from_id选择时,您都会丢失空白选项。第二个版本会在您每次选择区域时添加并选择一个空白选项:

jQuery ->
facilities = $('#call_transfer_from_id').html()

update_facilities = ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()

if options
# Set the options
$('#call_transfer_from_id').html(options)
# Add in a blank option at the top
$('#call_transfer_from_id').prepend("<option value=''></option>")
# Ensure that the blank option is selected
$('#call_transfer_from_id option:first').attr("selected", "selected");
else
$('#call_transfer_from_id').empty()

$('#call_region_id').change ->
update_facilities()

update_facilities()

关于jquery - CoffeeScript 在更改和加载时动态选择表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com