1

I have a simple script that dynamically generates buttons. Clicking on a button generates an error message in the console: "Uncaught SyntaxError: Unexpected token ')' (at (index):1:8)". Why is this error being generated, and how do I prevent it?

<button onclick="delete();">A Pet</button>
outis
  • 75,655
  • 22
  • 151
  • 221
DennisM
  • 359
  • 1
  • 3
  • 13
  • How does `console.log(data)` look like? – IT goldman Jun 30 '22 at 21:49
  • 3(index):21 This is data: [object Object],[object Object],[object Object] :3000/favicon.ico:1 Failed to load resource: the server responded with a status of 404 (Not Found) (index):1 Uncaught SyntaxError: Unexpected token ')' (at (index):1:8) The first two bits showed up before I pressed the button. – DennisM Jun 30 '22 at 22:09
  • Try to change const by var : var purchase = this.id; – SKJ Jun 30 '22 at 22:13
  • So the data is coming alright. How does `console.log(data[0])` look like?. Also you didn't close the `

    ` tag.

    – IT goldman Jun 30 '22 at 22:14
  • This is data: [object Object]. Closed the h2 tag, changed const to var. Neither worked. – DennisM Jun 30 '22 at 22:29
  • The given sample doesn't produce the given error for me. Please rewrite it as a [mcve]. Note you can use [SO Snippets](//meta.stackoverflow.com/q/269753/90527) to create a [live example](//meta.stackoverflow.com/q/358992/90527) that runs from the question itself. Also, please include platform info (such as browser(s) used). – outis Jun 30 '22 at 23:12
  • The `data[0]` should have been an `{object}` not a string `[object Object]`. – IT goldman Jun 30 '22 at 23:16

1 Answers1

2

delete is a keyword, and not valid as a function name. When the JS engine encounters delete() in the click handler body, it interprets it as a delete statement applied to (), which is an empty expression, and syntactically invalid.

To fix, use a non-keyword name. Note that it might be better to use addEventListener instead of an inline handler.

outis
  • 75,655
  • 22
  • 151
  • 221