I wrote a simple function to clear the input field on clicking a button. At first I had named the function clear()
and called it with oncick event in the button's html <input type="button" id="clr" onclick="clear()" value="Clr">
. My application uses other buttons that fire functions in the same manner no problem. However, on clicking the "Clr" button nothing would happen. I tried moving this script from the <head>
to the <body>
, tried making the button id different from the function name, etc... Finally, changing the function name from clear()
to clr()
made it work.
I checked javascript reserved words list and "clear" is not one of them... why would my function not fire when named clear()
?
Whole code for reference:
<!DOCTYPE html>
<html>
<head>
<title>変換天才</title>
<script>
//myriad converter function help from Stack Overflow user paxdiablo
function makeNum(num) {
num = num.replace(/,/g,""); //remove commas
var markers = "万億兆京該秭穣溝澗正載極";
var result = "";
//regroup in myriads
while (num.length > 4) {
if (markers.length == 0) {
result = "(?)" + num.substr(num.length-4) + result;
} else {
result = markers.substr(0, 1) + num.substr(num.length-4) + result;
markers = markers.substr(1);
}
num = num.substr(0, num.length-4);
}
return num + result;
}
function convert(){
var innum = document.getElementById("input").value;
var parsnum = (innum.replace(/,/g,""));
if (isNaN(parseInt(parsnum)) == true) {
document.getElementById("converted").innerHTML = "Please enter valid number.";
}
else {
var myriad = makeNum(innum);
document.getElementById("converted").innerHTML = myriad ;
}
}
function clr(){
document.getElementById("input").value = "";
document.getElementById("converted").innerHTML = "";
}
</script>
</head>
<body>
<div><p>Enter a large whole number.</p></div>
<input type="text" id="input"/>
<input type="submit" id="submit" value="Convert" onclick="convert()">
<br>
<input type="button" id="xthou" onclick="xThou()" value="thousand">
<input type="button" id="xmil" onclick="xMil()" value="million">
<input type="button" id="xbil" onclick="xBil()" value="billion">
<br>
<input type="button" id="xtril" onclick="xTril()" value="trillion">
<input type="button" id="xquad" onclick="xQuad()" value="quadrillion">
<input type="button" id="clr" onclick="clr()" value="Clr">
<br><br>
<div id="commaed"></div>
<div id="converted"></div>
</body>
</html>