Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript button onclick not working

<button onclick="hello()">Hello</button>

<script>
  function hello() {
    alert('Hello');
  }
</script>

This is my code. But it's not working. When I click on the button nothing happens.

like image 915
Martin W Avatar asked Mar 01 '17 11:03

Martin W


People also ask

How Onclick works in JavaScript?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

Can JavaScript click a button?

Javascript has a built-in click() function that can perform a click in code. Let's see an example of this below.

What is onclick button?

The Html <button onclick=" "> is an event attribute, which executes a script when the button is clicked. This attribute is supported by all browsers. It is also used to call a function when the button is clicked.


2 Answers

Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear.

<!DOCTYPE html>
<html>
<body>
  <button onclick="clear()">Clear</button>
  <button onclick="clear2()">Clear2</button>
  <script>
  function clear() {
    alert('clear');
  }
  function clear2() {
    alert('clear2');
  }
  </script>
</body>
</html>
like image 149
Michael Avatar answered Oct 19 '22 06:10

Michael


How about this?

<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>

P.S. You should place hello() above of the button.

like image 25
Kangjun Heo Avatar answered Oct 19 '22 05:10

Kangjun Heo