2

I am trying to make a one line JavaScript code software and right now it looks perfectly fine... until you hit the run button. Instead of running the code (like it's supposed to), it does absolutely nothing. So yeah, you can see the problem I am having with this.
Here's my HTML (in case you want to look over it):

<!DOCTYPE html>
<html>
  <body>
    <div class="default">
      <input type="text" id="codeInput" placeholder="document.write(`Hello, world!`)" value="document.write(`Hello, world!`)" class="code">
      <br/>
      <button onclick="convertString()">Run</button>
    </div>
    <div class="default">
      <script type="text/javascript" id="code">
        document.write(`Hello, world!`)
      </script>
    </div>
  </body>
</html>

Here's my JavaScript:

function convertString () {
  let code = document.getElementById("codeInput").value
  document.getElementById("code").innerHTML = code
}

And here's my CSS (not sure why I put this in here, but you can look over it if you want to):

.code {
  color: #162;
}
.default {
  display: block;
  margin: 8px;
}

So uhh... I'm having trouble. can you please help me?
<h1>Thank you!</h1>
Edit 1 (4 Jul 2020): No, this is not the same as stackoverflow.com/questions/1197575. S/he was trying to use onload="" to do a <script></script> inside the onload="". I am trying to call a function with a separate run function in my JavaScript and using a separate <script></script> tag.

Makyen
  • 31,849
  • 12
  • 86
  • 121

2 Answers2

2

In your html code, you're referring to a function (convertString()) which is defined outside the html page, in a separate file. You need to reference the JS file from your HTML page

<script src="path/to/script.js"/>

It is usually better to include JS files at the bottom of the page, in order for the browser to download every other file and start its JS engine at last

luco5826
  • 404
  • 3
  • 6
  • @COArSeD1RTxxx do you have a separate javascript file? Where is your `convertString()` function written? The code I suggested doesn't work because you need to change the path to the source js file – luco5826 Jul 04 '20 at 16:03
  • *sigh*. Yes, I do have a searate javascript file – Coarse Rosinflower Jul 16 '20 at 14:31
2

function convertString() {
  let code = document.getElementById("codeInput").value
  document.getElementById("code").innerHTML = code
}
.code {
  color: #162;
}

.default {
  display: block;
  margin: 8px;
}
<body>
  <div class="default">
    <input type="text" id="codeInput" placeholder="document.write(`Hello, world!`)" value="document.write(`Hello, world!`)" class="code">
    <br/>
    <button onclick="convertString()">Run</button>
  </div>
  <div class="default">
    <div id="code"></div>
  </div>

it is not good to called script tag and render something there sometimes it won't work if it is not the JavaScript code

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39