2

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Antoine
  • 559
  • 8
  • 21

3 Answers3

2

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();
}
Saumil
  • 2,521
  • 5
  • 32
  • 54
  • Note that the OP had his JS code in a separate file (`corel.js`). It would be good to demonstrate how he could implement this solution in a lined JS file. – Sumner Evans Jun 14 '15 at 01:02
1

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

Community
  • 1
  • 1
Striker
  • 507
  • 4
  • 11
0

Try also:

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