Week 4: Design a HTML page with required JavaScript that takes a
number from one text field in the range of 0 to 999 and shows it
in another text field in words. If the number is out of range,
it should show “out of range” and if it is not a number, it
should show “not a number” message in the result box.
Program:
<html>
<head>
<script>
function conversion()
{
var d,m,str,str2;
str=" ";
var ones=new
Array("","One","Two","Three","Four","Five","Six","Seven","Eight"
,"Nine");
var tens=new
Array("","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety");
var str2=new
Array("Ten","Eleven","Twelve","thirteen","fourteen","Fifteen","S
ixteen","Seventeen","Eighteen","Ninteen");
var n=document.getElementById("num").value;
if(n<0)
{
alert("Enter a Positive Number");
exit;
}
if(n>999)
alert("Out of Range");
if(n=="")
alert("Enter a Valid Number");
else if(n==0)
alert("Zero");
else
{
m=n.toString();
if(m.charAt(0)=='0'&&m.length>1)
{
m=m.substring(1,m.length)
}
x=m.length;
if(x==3)
{
var c2=parseInt(m.charAt(2));
var c1=parseInt(m.charAt(1));
var c0=parseInt(m.charAt(0));
if(c1==1)
{
str+=ones[c0]+" Hundred "+ str2[c2];
}
else
{
str+=ones[c0]+" Hundred "+
tens[c1]+ones[c2];
}
}
if(x==2)
{
var c1=parseInt(m.charAt(1));
var c0=parseInt(m.charAt(0));
if(c0==1)
{
str+= str2[c1];
}
else
{
str+= tens[c0]+ones[c1];
}
}
if(x==1)
{
var c0=parseInt(m.charAt(0));
str=ones[c0];
document.numberstring.wordstxt.value=str;
}
//document.numberstring.wordstxt.value=str;
document.getElementById("spell").value=str;
}
}
</script>
</head>
<body>
<h1 align="center"> Number to Words</h1>
<form name="numberstring">
Enter a number between 0 and 999
<input type="text" name="number" id="num"><br><br>
Number in Words
<input type= "text" name="wordstxt" id="spell"
disabled><br><br>
<input type="button" value ="convert"
onClick="conversion()">
<input type="reset">
</form>
</body>
</html>