Hi,
I have a form that contains two input fields used for a calculation.
When either one of these fields changes values, a
is updated with
the sum of these two fields. Right now, I am using observe_form to call
an action in my controller that performs the calculation. An RJS
template takes care of replacing my
with the new sum.
However, I want to change this approach so I am not making an AJAX
request to the server whenever the form is updated. I’d almost rather
have a “Calculate” button that will instantly perfrom the calculation
and update my
without a server request. What is the best way to
do this? Do I need to write a custom javascript function to grab the
form data and parse it? Are there Rails helpers or RJS statements that
will do this?
Thanks in advance for any help.
Brandon
This is untested, but from the API something like:
observe_form ‘my_form’, :function => ‘recalulate()’
And define your recalculate method in a javascript file, eg
application.js.
function recalculate() {
var value1 = Number($F(‘field_one’)) || 0;
var value2 = Number($F(‘field_two’)) || 0;
return value1 + value2;
}
You probably don’t need to observe the entire form though, you may be
able
to save some events by just observing the two fields you care about.
-Jonathan.
Jonathan V. wrote:
This is untested, but from the API something like:
observe_form ‘my_form’, :function => ‘recalulate()’
And define your recalculate method in a javascript file, eg
application.js.
function recalculate() {
var value1 = Number($F(‘field_one’)) || 0;
var value2 = Number($F(‘field_two’)) || 0;
return value1 + value2;
}
You probably don’t need to observe the entire form though, you may be
able
to save some events by just observing the two fields you care about.
-Jonathan.
Jonathan,
Thanks for your help… I was able to write the recalculate function
like you said. However, once I return the sum from the function, I am
having trouble displaying it on the page. I have :update =>
‘display_sum’ as a parameter to my observe_form function, but the
display_sum
is not being updated with the sum. Am I doing
something wrong?
Brandon S. wrote:
var value2 = Number($F(‘field_two’)) || 0;
Thanks for your help… I was able to write the recalculate function
like you said. However, once I return the sum from the function, I am
having trouble displaying it on the page. I have :update =>
‘display_sum’ as a parameter to my observe_form function, but the
display_sum
Your custom function needs to do the actual page modification itself,
much like the RJS would have. In fact, an easy way to implement this
would be to use FireBug to see the RJS response of your previous
version and then just stuff the whole thing into a function with the
appropriate parameters replaced…
_Kevin
Get rid of :update => ‘display_sum’ and replace it with :function =>
‘recalculate()’.
-Jonathan.