Drew Rush
Drew Rush

Reputation: 720

option_for_select in js.erb

I have this in file dvbd.js.erb and it works fine. The expected behavior is that the Dave div will have the set of name and id listed inside of it.

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>


$("#dave").html("<%= @dimvers.collect { |d| [d.name, d.id]} %>");

This is in applications.js, and the .post calls dvbd.js.erb fine:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

$.fn.subSelectWithAjax = function() {
  var that = this;

  this.change(function() {
    $.post("/dimensions/dvbd", {id: that.val()}, null, "script");
  });
}

$(document).ready(function(){
$("#dimver_dimension_id").subSelectWithAjax();
});

However, when I change the code in dvbd.js.erb to the following, it does not work. I expect it to change the options for select box #dimension_id. But instead it only changes the select box to have no contents/options if @dimvers happens to return no matching records. Then #dimension_id is no longer responsive.

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>

$("#dimension_id").html("<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>");

Here is the code in show.html.erb:

<div id = 'hierarchypanel'>
    <%= collection_select(:dimver, :dimension_id, Dimension.all, :id, :title ) %>
    <%= collection_select(:dimension,:id, @dimension_versions,:id, :name)  %>
</div>

Upvotes: 0

Views: 896

Answers (2)

jvnill
jvnill

Reputation: 29599

try passing the html to escape_javascript

$("#dimension_id").html("<%= escape_javascript options_for_select(@dimvers.collect { |d| [d.name, d.id] }) %>");

Upvotes: 1

sameera207
sameera207

Reputation: 16629

best way is to have a partial and have the select_tag in the partial, then call that partial from your .js.erb

Ex:

#_select_partial.erb
<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>

#dvbd.js.erb
$("#dave").html("<%= raw escape_javascript(render(:partial => 'select_partial')) %>")

Upvotes: 0

Related Questions