Let’s say you have a web form in your HTML document where you have a field and you are entering a number in this field and getting that number in JavaScript variable but when you try to add that variable to another variable you get error NaN which means for JavaSCript Not and Integer and javaScript cannot perform math functions or properties on such strings. For that purpose we have some javaSCript built in functions which we get in javaScript and we do not have need to re write them. We also call them global functions cause they are available inside script everywhere. To convert a string into integer we use function parseInt(); in JavasCript and to convert into float we use parseFloat() same for double numbers parseDouble(); so on. Let’s see an example.
We have a javascript function which take 2 values from 2 input type text fields in html form and calculate them and show their result on windows. Let’s say we have 2 fields in our HTML form and they both have their ID f_1 and f_2 we will get their values via javascript and then we will calculate and alert result in a box.
[code lang=”html”]
<input type="text" onchange="calculate();" id="f_1" value="22.22" />
<input type="text" onchange="calculate();" id="f_2" value="889.99" />
[/code]
Now we have 2 fields in html form and they have their default values but when we will change their values javaScript will call its function automatically cause we are calling javaScript function onchange even for text form in html document. Let’s write a JavaScript function now. Remember you can declare javaScript code anywhere in your document but not before <head> start, and not after </body> body ends, and not between body end and body start.
[code lang=”js”]
function calculate() {
first_number = document.getElementById("f_1").value;
second_number = document.getElementById("f_2").value;
//we are converting both numbers to float cause they are strings by default.
first_number = parseFloat(first_number);
second_number = parseFloat(second_number);
alert(first_number+second_number);
}
[/code]
Well this function will automatically run after each change on both fiels. First line of this code gets values of text fields from html form by their id and save them into a variable but by default that is coming in a string that’s why we have to change that to an integer type as we know Integers cannot handle decimal values that’s why we are using float now our both variables are float type they can save numbers they can calculate numbers after decimal then we are calling javaScript build in function alert to calculate both and show on screen.
Here we used 3 javaSCript build in Functions in which we have alert(); parseFloat(); getElementById();. Feel free to post your questions if you have.