Javascript Question

button onclick wont call the javascript function

I am calling a function on a button click. But the function is not getting called. I dont know what I am doing wrong. Please help.



<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function clear() {
document.getElementById('inp').value = "";
}
</script>
</head>

<body>
<input type="text" id="inp" name="">
<input type="button" onclick="clear()">
</body>
</html>




Answer

clear is not a reserved word but its calling document.clear instead. Try updating name of function

Sample

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clear1() {
      document.getElementById('inp').value = "";
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clear1()">
</body>
</html>

Sample - Override document.clear

Note: its a bad practice to override document/window/prototype functions. This is just for demonstration purpose.

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clear1() {
      document.getElementById('inp').value = "";
    }
    document.clear = function(){
      console.log('My clear function')
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clear()">
</body>
</html>

Reference

Is “clear” a reserved word in Javascript?

Comments