deeraj
deeraj

Reputation: 148

Selecting item dynamically in rails

i am attempting to do a dynamic select here using rails and jquery. the code is as follows

<div class = "line_items">  

<%- calc = Hash[Item.all.map{|p| [p.id, p.quantity]}].to_json %>

<div class = "item"><%= f.collection_select :item_id,Item.all,:id,:title, :prompt => "Select a Item", input_html: {data:{calc: calc} %></div>

   <div class ="quantity"> <%= f.text_field :quantity %></div>
/*rest  of code*/
</div>

javascript for the view is as follows

jQuery(document).ready(function(){
    jQuery('.item').bind('change',function() {
    var selectElement = jQuery(this);
    var  itemSelected = jQuery('.item:selected').val();
    var wrapperDivElement = selectElement.parent(".line_items");
    var quantity= eval(selectElement.data("calc"))[itemSelected];
    jQuery(".quantity", wrapperDivElement).val(quantity);
  });
});

when i change the item i am getting the following error eval(selectElement.data("calc"))[itemSelected] is undefined in firebug. Can anyone point out where i am going wrong? also any better way to get the quantity. i feel the method i am doing is crude. any guidance would be helpful. Thanks in advance.

Upvotes: 1

Views: 202

Answers (2)

bharath
bharath

Reputation: 623

jQuery(document).ready(function(){
    jQuery('.item select').bind('change',function() {
    var selectElement = jQuery(this);
    var  itemSelected = selectElement.val();
    var wrapperDivElement = selectElement.parents(".line_items");
    var quantity= eval(selectElement.data("calc"))[itemSelected];
    jQuery(".quantity input", wrapperDivElement).val(quantity);
  });
});

i guess the value of itemSelected was not getting detected, hence the error. the above redefined code should work. But i strongly urge you not to get data like this. its better to do a json call or ajax call to get the related data from the controller. and use parents instead parent in the code:)

Upvotes: 1

Hugo Logmans
Hugo Logmans

Reputation: 2252

Ik think you mixup the reference by index and the reference by ID. I'm no Javascript wizard, but you fill the hash with a list of . Then you get the 'val'-value in the change event. That contains an integer, but that is not the index.

Then you request in Javascript the item with index val, not the item with value val. Maybe javascript cannot distinguish between them because both need an Int...

it's this line:

var quantity= eval(selectElement.data("calc"))[itemSelected];

Upvotes: 0

Related Questions