Search code examples
javascripthtmlfunctioninnerhtml

How do I add a function to a btn.innerHTML in Javascript?


I'm trying to make a short sort of choice adventure HTML game for a school project. I have added a little typing section for a character name, which the game will use to refer to the player throughout.

I've gotten the username working, so it refers to the player as the text entered in the 'typing section'. However, I'm not very experienced and I've only gotten the page to refer to the player's name in a function. I've tried in the past to 'exchange' variables over to another page-but I couldn't figure it out so I've resorted to keeping it all on one page like this. If there're any alternative methods that also allow an inserted username to be used, it'd be appreciated.

function othername() {
  var input = document.getElementById("userInput").value;
  document.write("`Greetings, ");
  document.write(input);
  document.write("!`")
  var btn = document.createElement("BUTTON");
  btn.innerHTML = "Destroy";
  document.body.appendChild(btn);
  btn.innerHTML.onclick = function() {
    myFunction()
  };
  document.body.appendChild(btn);
}


function myFunction() {
  document.getElementById("userInput").value;
  document.write("aaaaaaaaaaaaaaaaah");
}
<form id="form" onsubmit="return false;">
  <input style="position:absolute; left:40%; top:40%; width:19.7%;" type="text" id="userInput" />
  <input style="position:absolute; left:40%; top:42%; width:20%;" type="submit" onclick="othername();" />
</form>

I expected to be able to assign a function to the btn variable through .onclick = function(){myFunction()}; and document.body.appendChild(btn); as it seems to have done previously with creating the "Destroy" button.


Solution

  • You don't add an onclick event to a button's content. You add it to the button:

    btn.onclick = myFunction;
    

    Note: Calling document.write() after the page first loads (for example, via an onclick handler like you have done) will cause the entire page to be deleted and replaced with the content of what you've written.

    In your case the page will contain only "!`" because first you are deleting the entire page to write "Greetings" then you delete the "Greetings" and overwrite it with "!`"

    Use innerHTML instead.