0

I have a simple form that, in jsfiddle I've simplified even further:

https://jsfiddle.net/mvw1nt5L/

Basically I have a table with just a header row. Above it I have an "Add" button which each time it gets clicked is supposed to add a row to the table.

my button element is ...

<button id="addMeeting" type="button" onclick="addMeeting();" > Add A Meeting </button>

and the associated JS function is simply

function addMeeting() {
alert("add button clicked");
return false;
}

Real, real simple! But it doesn't work. the JS code is contained directly in the html document as a script tag.

What am I doing wrong? TIA for any help!

Gus

GusV
  • 15
  • 5
  • not able to reproduce the error. Working fine for me – ellipsis Feb 28 '19 at 19:07
  • Gustaaf, there has to be a problem with the surrounding HTML. Is this an existing page? Its possible your event is being overwritten. Can I post a suggested edit that will help determine possible overwrite. – Bibberty Feb 28 '19 at 19:08
  • Your jsfiddle is set up so all the code is run onload. So it is not available on global scope. Your code looks like `window.onload = function () { function addMeeting() {} }` Adjust the fiddle so it runs in the head or end of the body. – epascarello Feb 28 '19 at 19:19

2 Answers2

1

It is a conflict between an element ID on your form and the function name. Or maybe not so much a conflict as a scoping issue. I've honestly never encountered this before until I tried to solve your problem. Very strange. Here's a more detailed explanation:

Why JS function name conflicts with element ID?

Spidy
  • 39,723
  • 15
  • 65
  • 83
  • Spidy, this is interesting. I used addEventListener on Gustaafs fiddle and it fixes the issue tho. – Bibberty Feb 28 '19 at 19:17
  • Spidy, thank you so much. That was it. When I changed the ID of the button element from "addMeeting" to "addMeetingButton", it started working. – GusV Feb 28 '19 at 19:42
  • @Bibberty That's because using addEventListener is executed from a different scope then the html onclick="". Just weird web things :) – Spidy Mar 01 '19 at 00:22
0

it seems it's a loading and scope issue. If you place a script tag before the html it will work just fine:

<script>
function addMeeting() {
      alert("add button clicked");
      return false;
    }
</script>
    <button id="addMeeting" type="button" onclick="addMeeting()"> Add A Meeting </button>

alternatively you can also explicit use the window object:

window.addMeeting = function() {
      alert("add button clicked");
      return false;
    }

and:

<button id="addMeeting5" type="button" onclick="window.addMeeting();"> Add A Meeting </button>
Mateus Amorim
  • 96
  • 1
  • 5