Is there a way to update form field data using Ajax? For example, I
want a select field with, say, phone numbers in a form. Then I’ll use
observe_field to monitor changes, and when the user selects a phone
number, the ajax call will update a description field in the same form
with, say, the person’s name related to the phone number.
I’ve successfully got the ajax call working, and, since the second field
is in a table, I’ve given the table cell an id and told the ajax call to
update that cell. It then rebuilds the input field with the new data.
It all works fine, and the new data appears in the correct field as
expected, but when I post the form, it treats the description field as
empty.
I’ve tried submitting the form by just typing data in the description
field, and it works correctly, but if I select something in the select
field and it updates the description field, the form always treats it as
empty.
Is there a way to update form field data using Ajax? For example, I
want a select field with, say, phone numbers in a form. Then I’ll use
observe_field to monitor changes, and when the user selects a phone
number, the ajax call will update a description field in the same form
with, say, the person’s name related to the phone number.
(…)
For select tag, the value to set is the option ID.
If you need to replace select values:
page[‘field_id’].length=0 @your_object.each do |obj|
page << “$(‘field_id’).options[$(‘field_id’).length]=new
Option(‘#{escape_javascript(obj.to_s)}’,#{obj.id})”
end
(Ok, to be honest, Ajax and java and rjs templates
are still pretty foggy generally.)
I recommend Cody F.'s RJS tutorial, available in PDF for from
O’Reilly
for $10. Best ten bucks I’ve spent on Rails so far. It won’t make you
an
expert, but I found it to be a dang good starting point.
page[‘field_id’].length=0 @your_object.each do |obj|
page << “$(‘field_id’).options[$(‘field_id’).length]=new
Option(’#{escape_javascript(obj.to_s)}’,#{obj.id})”
end
Just an fyi for anyone else who might be following this, I had to change
Option(’#{escape_javascript(obj.to_s)}’,#{obj.id})"
to
Option(’#{escape_javascript(obj.description.to_s)}’,#{obj.id})"
in order for it to work.
Thanks again Massimo.
Bill, thanks for the tutorial recommendation. My brain balks at the
idea of me trying to stuff some other new knowledge in there, but it’s
probably inevitable.
Shawn
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.