Abhi
Abhi

Reputation: 1574

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>

Upvotes: 0

Views: 69

Answers (3)

Rajesh
Rajesh

Reputation: 24955

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?

Upvotes: 5

Saeed ur Rehman
Saeed ur Rehman

Reputation: 737

<!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.

Upvotes: 0

Noni
Noni

Reputation: 369

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

Upvotes: 0

Related Questions