ovatsug25
ovatsug25

Reputation: 8606

jQuery in Rails app will not read values that have spaces. How do I get it to interpret these values?

I am trying to use jQuery to auto-update related select boxes in my Rails app. It works fine with values that have no spaces like "Barahona" or "Manzanillo" but it fails when I try something like "Puerto Plata" or "Santo Domingo".

Here is the error from the console when I select "Puerto Plata".

Uncaught Error: Syntax error, unrecognized expression: optgroup[label=Puerto Plata] 

I am using jQuery that is adopted from Railscasts #88 and listed here to select a Port and then filter the berths to only list Berths from that port.

Here is the 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()

Here is the view:

  <%= 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  %>

Upvotes: 1

Views: 334

Answers (1)

3coins
3coins

Reputation: 1342

You might want to use single quotes around the labels that have spaces. So your expression will become something like this.

options = $(berths).filter("optgroup[label='#{port}']").html()

Upvotes: 1

Related Questions