0

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>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Abhi
  • 1,512
  • 2
  • 22
  • 46

3 Answers3

5

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?

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Change the function name because clear function make that issue. make the function name clearInput or what ever you convenient

Noni
  • 369
  • 2
  • 14
0
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clearTxtBox() {
      document.getElementById('inp').value = "";
    }
  </script>
</head>

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

Just change your function name and it will work.

Saeed ur Rehman
  • 727
  • 2
  • 10
  • 25