Search code examples
javascriptruby-on-railsruby-on-rails-2

How can I show a value in a javascript onchange?


I did an app in rails using javascript to do a sum.

But I have a problem when my value is nil or empty won't work and shows "NaN".

Could be a way to fix this or maybe show " 0 " insteaf of "NaN"?

Here is my controller

 def
   @soles = Client.sum(:money)
 end

The problem is when @soles is nil , I need a way to show 0.

 <input type="text" id="my_input1" value="<%=  @soles  %>" />
 <input type="text" id="my_input2" onchange="doMath();" />
 <input type="text" id="sum" />

 <script type="text/javascript">
function doMath()
{
    // Capture the entered values of two input boxes
    var my_input1 = document.getElementById('my_input1').value;
    var my_input2 = document.getElementById('my_input2').value;

    // Add them together and display
    var sum = parseInt(my_input1) + parseInt(my_input2);
    document.getElementById('sum').value = sum;
}

I tried but doesn't work

@soles = 0

I will really appreciate help.

Thanks


Solution

  • Using isNaN javascript function like this :

    if (isNaN(sum))
        sum = 0;
    document.getElementById('sum').value = sum;