-3

I'm trying to write a simple code in JavaScript where selecting a button calls a prompt function, but the prompt never pops.

This is the HTML:

    <div id="btnDiv">
    <button type="submit" id="btn" onclick="submit"> send info </button>
    </div>

And this is the JavaScript code:

    document.getElementById("btn").onclick = function(){
    prompt("Thank you");
    }

What am I doing wrong?

  • Can you provide a fiddle with how you're structuring this? You could be trying to attach an event to an element that doesn't exist yet. Also, `prompt` expects an input. You want `alert` here. – Sterling Archer Sep 25 '16 at 22:18
  • Have you checked your browsers console for any error reports? – NewToJS Sep 25 '16 at 22:19
  • 1
    You need to attach the event handler after adding it in the DOM, otherwise `document.getElementById("btn")` won't find anything. – Spencer Wieczorek Sep 25 '16 at 22:27
  • Hi @SterlingArcher Archer, you're right, I changed the 'prompt' into 'alert'. This is my fiddle code, in which the function actually works (it didn't work locally): https://jsfiddle.net/hr2ss2b7/3/ NewToJS- Running the code locally, I get following error: _Uncaught ReferenceError: submit is not defined_ Spencer, I'll try it. Thank you :) – Rakefet Zeiman Sep 27 '16 at 14:41

1 Answers1

0

Make sure that the JS code is loaded after the HTML content, you can use onLoad event:

window.onload=function(){
    document.getElementById("btn").onclick = function(){
      prompt("Thank you");
    }
};
Marcin
  • 1,514
  • 1
  • 12
  • 27