Rails アプリで関連する選択ボックスを自動更新するために jQuery を使用しようとしています。「Barahona」や「Manzanillo」などのスペースのない値では問題なく動作しますが、「Puerto Plata」や「Santo Domingo」などを試すと失敗します。
「Puerto Plata」を選択したときのコンソールからのエラーは次のとおりです。
Uncaught Error: Syntax error, unrecognized expression: optgroup[label=Puerto Plata]
Railscasts #88 から採用され、ここにリストされている jQuery を使用してポートを選択し、バースをフィルタリングしてそのポートからのバースのみをリストします。
jQuery は次のとおりです。
jQuery ->
berths = $('#voyage_berth_id').html()
console.log(berths)
$('#voyage_port_id').change ->
port = $('#voyage_port_id :selected').text()
options = $(berths).filter("optgroup[label=#{port}]").html()
console.log(options)
if options
$('#voyage_berth_id').html(options)
$('#voyage_berth_id').parent().show()
else
$('#voyage_berth_id').empty()
$('#voyage_berth_id').parent().hide()
ビューは次のとおりです。
<%= f.label :port_id %>
<%= f.collection_select :port_id, Port.order(:name), :id, :name %>
<%= f.label :berth_id %>
<%# f.collection_select :berth_id, Berth.order(:name), :id, :name %>
<%= f.grouped_collection_select :berth_id, Port.order(:name), :berths, :name, :id, :name %>