I have the following model:
create_table "mouldings", :force => true do |t|
t.string "suppliers_code"
t.datetime "created_at"
t.datetime "updated_at"
开发者_如何学运维 t.string "name"
t.integer "supplier_id"
t.decimal "length", :precision => 3, :scale => 2
t.decimal "cost", :precision => 4, :scale => 2
t.integer "width"
t.integer "depth"
end
When a user selects a moulding on a form I want to get the cost of the moulding by ajax and use it to get a generate a quote using javascript. Here is the select tag from the form:
<select id="order_item_moulding_1_id" name="order_item_moulding_1[id]">
<option value="">Select a moulding 1</option>
<option value="1">123 589 698</option>
<option value="2">897 896 887</option>
<option value="3">876 234 567</option>
</select>
Here is part of the javascript file:
$(document).ready(function () {
$('#order_item_moulding_1_id').change(function () {
var moulding_1_price = ;
});
});
How do I use Ajax to set the variable moulding_1_price?
If you wanted to do it in your rails controller via ajax, you'd just set the value of each option to the ID of the molding you were looking up, and send that to your controller with jQuery's ajax method:
var theVal = $('#order_item_moulding_1_id').val();
var theURL = '/someUniqueRoutingKeywordSuchAsMouldingAjax/' + theVal;
$.ajax({
url: theURL
});
Then make sure you have a route set in your routes.rb file:
match 'someUniqueRoutingKeywordSuchAsMouldingAjax/:id', :to => 'yourMouldingsController#ajaxMouldings'
And in your yourMouldingsController, define a custom method:
def ajaxMouldings
@moulding = Moulding.find(params[:id])
end
By default, this will render ajaxMouldings.js.erb. So in your views, make sure you have a file with that name. That's embedded javascript, so you can use it to replace some div on your page where you want that information to appear:
// in ajaxMouldings.js.erb
// be sure to escape any dynamic values!
alert('Hey, it worked!');
var theHTML = '<div class="moulding_title"><%= escape_javascript(@moulding.title) %></div><div class="moulding info"><%= escape_javascript(@moulding.info) %></div>';
$('#someUniqueDiv').html(theHTML);
Obviously, you'll want to throw in a few safeguards against bad data, etc... but that should get you on the right track.
You could do an ajax call to retrieve the data, or you could use HTML5 data attribute.
For the second solution, you would add data-price
attribute to your options tags, so it would look like this:
<option value="1" data-price="123">123 589 698</option>
<option value="2" data-price="456">897 896 887</option>
<option value="3" data-price="789">876 234 567</option>
Then, in your JS file:
$(document).ready(function () {
$('#order_item_moulding_1_id').change(function () {
var moulding_1_price = $(this).find('option:selected').attr('data-price');
});
});
精彩评论