Home > other >  Interpreting Input in Javascript
Interpreting Input in Javascript

Time:10-15

I made some HTML code in replit.com.

Please excuse me if the question I ask is very dumb, since I am new to HTML & JS.

I want the user to type something in the input field and click the "Click Me" button. I expected the button to change its text to whatever the user typed. But instead, it just went blank.

Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <label for="text">Type Some Text:</label><br>
    <input type="text" id="type" name="text"><br><br>
    <button type="button" style="background-color: khaki; margin-left: 20px; padding-left: 30px; border: solid 5px; border-radius: 40px; padding-right: 450px; font-size: 18px" onclick="Click()" id="click">Click Me!</button>
    <script>
      function Click() {
        text = document.getElementById("type").innerHTML;
        document.getElementById("click").innerHTML = text;
      }
    </script>
  </body>
</html>

CodePudding user response:

https://codepen.io/jacobcambell/pen/OJjyoWW

A few things to consider here.

First, to get the value of an HTML input, you need to use .value instead of .innerHTML, for example:

text = document.getElementById("type").value;

Next, (optionally) you can just call alert() instead of window.alert() as most browsers know how to handle it correctly.

Finally, to change your button, you need to set the innerHTML of the button to your text variable, right now you're just setting it equal to "text" which is a string in JavaScript. You are literally making your button say "text"

Also, I would recommend using let to declare your variables here.

A final version of your Click function might look like:

function Click() {
    let text = document.getElementById("type").value;
    alert(text)
    document.getElementById("click").innerHTML = text;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use this:

function Click() {
        text = document.getElementById("type").value;
        document.getElementById("click").innerHTML = text;
      }

Also, you can also use this:

function Click() {
        document.getElementById("click").innerHTML = document.getElementById("type").value
}
  • Related