Javascript problem in converting value to int

0

I need 2 functions that take the value of a input and send it to another input this value +2, I had already asked this question here but it was for +3 and I got the solution, however I did another function with other name and other fields, and the result was NaN . Here is the code for +3 that works:

function tenta() {
    if(document.getElementById('ciclo').value == "")
    {
        document.getElementById('ciclo2').value = "2013"; //placeholder
         document.getElementById('ciclo2').style.color = "#bfbfbf";
    }else
    {
        document.getElementById('ciclo2').style.color = "black";
        var x = document.getElementById('ciclo').value;
        document.getElementById('ciclo2').value = parseFloat(x) + 3;
    }
}

and function equal, but returns NaN :

    function numeros2()
        {
            if(document.getElementById('ciclo3').value == "")
            {
               document.getElementById('ciclo4').value = "2013"; //placeholder;
                 document.getElementById('ciclo4').style.color = "#bfbfbf";
            }else
            {
                document.getElementById('ciclo4').style.color = "black";
                var xy = parseInt(document.getElementById('ciclo4').value);
                document.getElementById('ciclo4').value = xy + 2;
            }
        }

I have tried parseFloat , but it also does not work.

    
asked by anonymous 15.04.2016 / 16:34

2 answers

4

The problem is that parseInt("") gives NaN , that is, when the string is empty the parseInt gives this, which means " N ot a N umber ("Not a number").

You have to do this: var xy = parseInt(ciclo3.value || 0, 10); . This way he chooses zero if value is an empty string. You should note that empty string validates as "false" when converted to Boolean.

jsFiddle: link

    
15.04.2016 / 17:23
0

It may be that document.getElementById("ciclo").value is not returning a String. Not all DOM objects have the "value" property.

Check which object is being returned in this portion of the code and use the appropriate form to get the data you need.

If you clarify which Node returned from document.getElementById("ciclo") and HTML it will be easier to post a more specific response to your problem.

    
15.04.2016 / 17:01