开发者

Ruby on Rails, realtime calc

开发者 https://www.devze.com 2023-02-17 11:08 出处:网络
im learning RoR atm and im trying to code a calculator web开发者_C百科app. The thing is: I want that the operations are gettin calculated in realtime.

im learning RoR atm and im trying to code a calculator web开发者_C百科app. The thing is: I want that the operations are gettin calculated in realtime. So if i type in 2+2 the calc says 4 without that i pressed some "CALC NOW" button.

Can someone give me some hints how i could to that? Do i need to learn AJAX for that?


You can do the calculations on the client side using JavaScript only. Or you can use JavaScript-driven automatic form submit or AJAX to send the input to the server and calculate with Ruby on Rails.

To calculate on the server side:

routes:

resources :calculators

CalculatorsController

def create
  @sum = eval(params[:data])
end

app/views/calculators/create.js.erb

document.getElementById("sum").innerHTML = <%= @sum %>

app/views/calculators/index.html.erb

<%= form_tag calculators_path, :method => :post, :remote => true do %>
  <%= text_field_tag :data, nil, :onkeyup => "this.form.sub.click()" %> = <span id="sum"></span>
  <%= submit_tag "ok", :name => "sub" %>
<% end %>

now go to /calculators and enjoy

0

精彩评论

暂无评论...
验证码 换一张
取 消