Ryan Williams
2006-Apr-10 17:18 UTC
[Rails] autocomplete 2nd field based on 1st field''s input
I''m trying to populate a field named "file_name" based on the input of a field named "title". So, for instance, based on the following input in the "title" field: My Title Is Awesome I would want the following "file_name" to be autocompeted on the fly: My_Title_Is_Awesome I''ve been going over all the autocomplete examples out there, but since they all seem to apply only to pulling data from a model, I''m not sure how I could approach this. Surely others have done something like this in rails. Any suggestions? -- Posted via http://www.ruby-forum.com/.
Jeff Coleman
2006-Apr-10 17:41 UTC
[Rails] Re: autocomplete 2nd field based on 1st field''s input
Ryan Williams wrote:> I''m trying to populate a field named "file_name" based on the input of a > field named "title". So, for instance, based on the following input in > the "title" field: > > My Title Is Awesome > > I would want the following "file_name" to be autocompeted on the fly: > > My_Title_Is_Awesome > > I''ve been going over all the autocomplete examples out there, but since > they all seem to apply only to pulling data from a model, I''m not sure > how I could approach this. Surely others have done something like this > in rails. Any suggestions?I''m not sure of the exact syntax of the code, but in theory what you might want to do is use the observe_field function in your view, to observe the title field. You could set observe_field to call a method in your controller which uses RJS to set the innerHTML of your file_name field. Look into observe_field, and I''m not sure exactly how you set the innerHTML with RJS, but that''s where I''d start. Jeff Coleman -- Posted via http://www.ruby-forum.com/.
You can try something like this: <%= text_field( ''some_class'', ''title'' ) %> <%= observe_field( ''some_class_title'', :function => "$(''some_class_file_name'').value=value.toLowerCase().replace(/\s/g, ''_'')", :frequency =&mt; 0.5 ) %> <%= text_field( ''some_class'', ''file_name'' ) %> This should update the "file_name" field using the contents of "title" and format the string according to whatever you want. In this case, the "observe_field" method will work locally without Ajax calls. In case you need a more complex logic, the function could be executed in the controller. In order to update the second field you could have an empty DIV or something at the bottom of the page and print from the controller the javascript block. Should also work. R.
Yes! Thanks! This did indeed work: <pre> <%= text_field( ''some_class'', ''title'' ) %> <%= observe_field( ''some_class_title'', :function => "$(''some_class_file_name'').value=value.toLowerCase().replace(/\s/g, ''_'')", :frequency => 0.5 ) %> <%= text_field( ''some_class'', ''file_name'' ) %> </pre> -- Posted via http://www.ruby-forum.com/.