Monday, July 20, 2009

How to dynamically insert html code with Javascript and Rails

somePage.html.erb

<%= text_field("myObjectName", "someAttribute", "onchange" => "calculateMyVar()") %>

When the user moves out of the text field, the javascript will be called.

<% if @myVar.nil? %>

<% else %>
<%= @myVar %>
<% end %>

Notice that, in order for this to work the value between the td tags is empty. If you have some dynamic output tag as shown in the else section then the javascript will not work. The above code will work for new and edit cases.

Include the following javascript within the head section of the html.erb file.

function calculateMyVar()
{
var f1 = document.getElementById('field1').value;
var f2 = document.getElementById('field2').value;
document.getElementById('myVar').innerHTML = f1 - f2
}

No comments:

Post a Comment