Trigger JavaScript action on click?

408 Views Asked by At

I want to trigger some JavaScript code when the button is clicked. I want that when the button is clicked console.log() is triggered. My attempt:

corel.html :

<!DOCTYPE html>
<html>
<head>
    <title>Corelation</title>
    <script src="jquery-1.11.3.min.js"></script>        
    <script type="text/javascript" src="corel.js"></script>
</head>
<body>

<form id="tableVar">
  Variable 1: <input type="text" id="var1"><br>
  Variable 2: <input type="text" id="var2"><br>
  <button onclick="myFunction()">Click me</button>  <!-- type is button to not refresh -->
</form>

</body>
</html>

corel.js :

console.log("iniating app ...");
function myFunction() {
    console.log('yeah');
}

I do not understand what does not work ?

3

There are 3 best solutions below

1
On BEST ANSWER

The button is making the form submit hence you need to use preventDefault()

See this demo

Use this code,

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Corelation</title>
    <script src="jquery-1.11.3.min.js"></script>        
    <script type="text/javascript" src="corel.js"></script>
</head>
<body>

<form id="tableVar">
    Variable 1: <input type="text" id="var1"><br>
    Variable 2: <input type="text" id="var2"><br>
    <button onclick="myFunction(event)">Click me</button>  <!-- type is button to not refresh -->
</form>

</body>
</html>

Corel.js

console.log("iniating app ...");
function myFunction(event) {
    console.log('yeah');
    event.preventDefault();
}
0
On

Try also:

<button onclick="return myFunction()">Click me</button>
function myFunction() {
    console.log('yeah');
    return false
}
0
On

Clicking on the button refreshes the page. If you open up console and select preserve log you will see it works.

If you do not want to refresh then you need to add a return to your function like this:

function myFunction() {
    console.log('yeah');
    return false;
}

And on your html the button code should be as follows:

<button onclick="return myFunction()">Click me</button>

Reference: prevent refresh of page when button inside form clicked