简体   繁体   English

如何在javascript onchange中显示值?

[英]How can I show a value in a javascript onchange?

I did an app in rails using javascript to do a sum. 我使用JavaScript在Rails中做了一个应用程序来求和。

But I have a problem when my value is nil or empty won't work and shows "NaN". 但是,当我的值为nil或为空时,我将遇到问题,并且显示“ NaN”。

Could be a way to fix this or maybe show " 0 " insteaf of "NaN"? 可能是解决此问题的一种方法,或者显示“ NaN”的“ 0”错误消息?

Here is my controller 这是我的控制器

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

The problem is when @soles is nil , I need a way to show 0. 问题是当@soles为nil时,我需要一种显示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 谢谢

Using isNaN javascript function like this : 使用isNaN javascript函数,如下所示:

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

you can try something like this 你可以尝试这样的事情

if(!document.getElementById("yourElementIDName")){

  alert("DOES NOT EXIST");

} 

else {

    alert("Object Exists - You can script to this object");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM