Button in JavaScript is not working as expected

Viewed 72

An error message appeared after adding my button which calls a function in JavaScript. I cannot find the problem.

Sorry for the faults. I am French and I'm using Google Translate.

Here is the part of the code in question:

document.getElementById("jouer").onclick = start();
document.getElementById("jouer").onclick = function () { alert('defis[0]'); };

<input id= "jouer " type="button" value="jouer" click="start()"/>;

And the error message is:

Uncaught SyntaxError: Unexpected token '<'

3 Answers

It seems like you are trying to run both JS and HTML in one file.

To get it to work, you need to create a separate file with HTML stuff and use <script src="your-js-file.js"></script> in the HTML file for the browser to be able to run JS.

function start() {
  alert('i am working')
};

document.getElementById('jouer2').onclick = start
<input id= "jouer " type="button" value="jouer" onclick="start()"/>;
<input id= "jouer2" type="button" value="jouer2"/>;

target.onclick = functionRef;

functionRef is a function name or a function expression. so you can try this document.getElementById("jouer").onclick = start; also you don't need the click attribute in the element as you are targeting the DOM element above. if you want to trigger a function directly from some element then pass onclick attribute with the function call and you won't need to target like this document.getElementById("jouer").onclick reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

The only error i see is that you have a whitspace in the id selector in the input "jouer". this causes the script to not be able to grab the element. Otherwise, the error Uncaught SyntaxError: Unexpected token '<' means that you are trying to include a file (script) that it can't find.

Related