Pregunta

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

¿Fue útil?

Solución

Using isNaN javascript function like this :

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

Otros consejos

you can try something like this

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

  alert("DOES NOT EXIST");

} 

else {

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

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top