I''m trying to get some auto_complete_field stuff going, and I have them working for the most part, but I can''t quite get how the :on_hide option works. I''m hoping that I can populate a hidden field with the id of the chosen record with it...is that going to be possible? Thanks for your help. -- Posted via http://www.ruby-forum.com/.
Forrest Thiessen
2005-Dec-21 05:38 UTC
Re: How do you use :on_hide in auto_complete_field?
toby sterrett <tsterrett@...> writes:> I''m trying to get some auto_complete_field stuff going, and I have them > working for the most part, but I can''t quite get how the :on_hide option > works. I''m hoping that I can populate a hidden field with the id of the > chosen record with it...is that going to be possible?You give the :on_hide parameter a Javascript fragment that you want to have executed on the client (in the browser) at the appropriate time. It can be any Javascript you want. Since your Javascript executes on the client, it has full access to anything in the DOM of the page you rendered. . . but (other edge of the sword) since it''s on the client, it has NO access to anything in your Rails code (unless, of course, your Javascript makes an XmlHttpRequest call back to Rails). So, if you want the Javascript to do something with Rails data, you have to make sure you either render the data on the page somewhere, or you include it in your Javascript fragment directly yourself. You said you want to populate a hidden field with the id of a selected record; yes, that should be no problem. I haven''t tested this, but it should be something like: :on_hide => "$(''hiddenField_id'').value = $(''input_id'').value" A few points about this: * Because Rails includes the Prototype library, you can use it''s shorthand $ function to refer to DOM elements by their ID. * You have to be careful with your quotes--both Ruby and Javascript have their own quoting requirements, and you need to watch out you don''t have one step on the other''s toes. * Be aware that just because the user selected an item on the auto-complete list, that doesn''t mean they''re not going to type more characters into input field manually--thus making the ID in your hidden field wrong. If you absolutely want the hidden field to contain the ID of their selected record, you will probably need to do something more sophisticated. (I did something like this and ended up using an observe_field helper to watch what the user was typing, and then building my own version of auto_complete_field that put the auto-complete results into a select input, and then using some Javascript to copy the id of whichever item in the select input they selected into the hidden field. . . that way the hidden field was certain to contain the ID of the record they selected). --Forrest