I am trying to display a calculated value which is calculated from a variable that is passed to the function.
It gets the var value from an input field, converts it to a number value and then does the math, but it always returns NaN, unless i pass a straight up number as argument to the convertToCelsius function.
Where is the problem here? Maybe i have to capture the input fields value on keyup?
var getInput = document.getElementById('temp').value;
var theTemp = parseInt(getInput, 10);
function convertToCelsius(theTemp) {
return (5 / 9) * (theTemp - 32);
}
See, neither the number nor parseInt methods help here, I suspect this is because the value is not read at the right moment. Maybe should get the input value when the element loses focus or on keyup.
[quote=ādamiano, post:1, topic:228910, full:trueā]
It gets the var value from an input field, converts it to a number value and then does the math, but it always returns NaN,[/quote]
Well, that is exactly why i/ think this will need a function returning the value on keyup or onblur event. Does the above code work for you? Does not work for me:confused:
The problem is being caused by the use of āonfocusā rather than āfocusā in the text box clear handler which means it wonāt work. You are also calling var getInput = document.getElementById('temp').value;
before you have entered a number, so getInput has the text default value at startup (āEnter temperatureā), rather than a number.
The following script resolves these problems and works fine.
<script type="text/javascript">
var tempObj = document.getElementById('temp');
var demoObj = document.getElementById('demo');
var myTextObj = document.getElementById('myText');
tempObj.addEventListener('focus', function(){ if (!this.value == ""){ this.value = "";}} );
demoObj.addEventListener('click', function(){ myTextObj.innerHTML = (5/9)*(Number(tempObj.value) - 32)});
demoObj.innerHTML = "click here to convert values";
var x = document.getElementsByTagName('p');
for (var i = 0; i < x.length; i++){ x[i].style.transition = '0,5s'; x[i].style.color = "red"; }
</script>
The addEventListener() method is not supported in IE 8 and earlier versions, but you can use the attachEvent() method to attach an event handlers to the element in these cases. The addEventListener syntax uses āfocusā, while the attachEvent syntax uses āonfocusā.