Gabriel G.
Gabriel G.

Reputation: 1

Need help to show a operation with user inputs in ruby on rails

So, my company is working in a rails fleet manager, and i'm struggling to show in real-time a simple operation of a unit (amount * value) in real time to the user.

This is the .haml file where the form is show to user:

What is the best way to do it?

Upvotes: 0

Views: 87

Answers (1)

Juan Artau
Juan Artau

Reputation: 357

I think this has nothing to do with Rails. You can simple create a 'change' event listener in the input fields of your form to calculate it. If you are using turbolinks then you can do something like this:

document.addEventListener("turbolinks:load", function() {
  // Get the elements in DOM
  var amount = document.getElementById("amount");
  var unitValue = document.getElementById("unit_value");
  var result = document.getElementById("result");

  // Calculate and return unite values times amount.
  function calculate_total(unit, amount) {

    // If there is no value on input set 0 by default
    if (unit == "") {
      unit = 0
    }
    if (amount == "") {
      amount = 0
    }

    return parseInt(unit) * parseInt(amount)
  }

  // Set the event listener to inputs on user keyboard input
  amount.addEventListener("keyup", function(e) {
    result.value = calculate_total(unitValue.value, amount.value)
  });

  unitValue.addEventListener("keyup", function(e) {
    result.value = calculate_total(unitValue.value, amount.value)
  });
})

This code is not tested, but is to give you the idea.

Upvotes: 1

Related Questions