Unobtrustive JS Ruby on Rails, onclick to replace div contents with form elements
I have a simpl开发者_运维问答e piece of text inside a div tag as follows:
<div id="text">Value
<a href="/actual/link/incase/user/has/JS/turned/off" id="change_value"/>
</div>
I then have this javascript
$('change_value').observe('click', function(event){
$("text").update("something here!");
event.stop(); // Prevent link from following through to its given href
});
And this is all great. However i have two questions (first is my main issue):
How do i get it so that instead of updating the div with 'something here' it updates it with form elements, i.e. a form tag, a label, a textbox and a button to 'submit' the change. The idea is the user will be able to edit this field in-place on the page.
Where should i actually place my JS. I currently have it in application.js and run the function with window.onLoad...is that the only way? I assume so, as otherwise it whinges it can't find the element!
Thanks all!
I think your best option is to watch rails casts #196 and #197 :
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
These casts explain how to create nested models in form (of 3 levels) ; the part2 concentrates on the javascript part for actions such as add and delete.
Good viewing.
Question 1: You could make an AJAX call to whichever controller/action you need. Your controller will get the object you're looking for and then send down a js.erb template. The js.erb template could do something like this:
$('#change_value').update('<%= render :partial => @object %>');
Then your partial for that object type would contain the form you need. There is more on this approach in various Railscasts episodes. Episode 136 has good examples of this but uses jQuery, so you'd have to adapt it to Prototype syntax (although if you haven't tried jQuery I'd suggest giving it a shot). Episode 235 has lots of good stuff regarding UJS and shows examples for both jQuery and Prototype.
Question 2: No, it does not have to go in application.js. You can create another js file specific to that resource and include it in your layout for that resource. If that resource doesn't use a layout, I think you can still include it in your view.
精彩评论