views:

34

answers:

2

Hi,

I have this ruby on rails code

<%= builder.select(:serving_size_id, '') %>

I have not specified any options on purpose because I set the options in a different way when the page loads (using jQuery and Ajax).

The question: Is there any way I can get the value from the column "serving_size_id" but not change that line? I have a partial which I use it for new and edit and I think it would be sweet if I can do the setting of the selected index in JS.

Any ideas?

A: 

I'm not sure I completely understand your question, but if you want to set the value of the select field with JavaScript, you need to obtain the value in JavaScript at some point. I can think of two ways of doing this:

1) When you get the options via AJAX, have the server indicate which one is selected. This can be done by returning HTML <option> tags with selected="selected" set for one of them. To do this, your AJAX request is going to have to provide information about the object this select field is for (so the server can look up the object's current serving_size_id value).

2) When you render the field in your original partial, also render some JavaScript which sets the current value of the field, for example, underneath what you have above:

<%= javascript_tag "var ssid = '#{builder.object.serving_size_id}';" %>

Then, after the options are retrived via AJAX, the ssid variable is checked and the correct option is selected.

Alex Reisner
Thanks... I totally forgot that I can get the value by #{builder.object.serving_size_id}...
iHeartDucks
A: 

Hey iHeartDucks, using jQuery in rails is easy but a little more difficult than prototype.

ex: "div id="serving_size" class="nice" rel="<%=h num%>">Stuff Goes Here.../div>"

in application.js do the following:

//application.js

$(document).ready(function(){ if($('#serving_size'){ $('#serving_size').live("mouseover",function(){ //we are hovering over specific div id serving size if($('#serving_size').hasAttr('rel')){ alert($('#serving_size').attr('rel'); //your dynamic rel value, and fire function } } } if('.nice'){ $('.nice').live("mouseover",function(){ //we are now hovering over any item on page with class nice if($(this).hasAttr('rel')){ //we are now using jQuery object ref and finding if that obj has attr rel alert($(this).attr('rel')); // shows dynamic rel value } } } });

If you use the above code you should be able to do anything you want and fire any custom code from each of your set event callbacks.

The 'live' function in jQuery is great because it can be called on items that will eventually be on the page (eg. if you fill in something with ajax, jQuery will be prepared for that item being in the page)

I hope this help.

newfront