简体   繁体   中英

Display the name entered?

I'm learning JavaScript/HTML, and I need help to adjust the JS script function so that when the user clicks "submit" it will display the name that the user enters.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Names</title>
    <link type="text/css" rel="stylesheet" href="css/style.css"/>
    <script type="text/javascript" rel="script" src="js/scripts.js" defer></script>
</head>
<body>

  <label for="name">Your Name:</label>
  <input id="name" name="name" type="text"/> 

  <input id="submit-button" name="submit-button" type="submit" value="Submit"/>

  <h3>Result</h3>
  <div id="output">
            Form not submitted yet.
  </div>

<script>

function DisplayName(){
  document.getElementById('submit-btn').innerHTML = 
  document.getElementById("name").value;
  }
  console.log("Your name is: " + name);

</script>

</body>
</html>

We can make a couple adjustments and get this working just fine. The common method would be to add a click event listener to your button that once clicked will trigger a function.

Let's add this to your button: onclick="displayName() , note I am writing the function in camelCase. This is a good practice for js functions. Here's how your button looks now:

<input id="submit-button" name="submit-button" type="submit" value="Submit" onclick="displayName()"/>

Next let's do the javascript. We can keep it all in one simple function, the displayName() function.

function displayName(){
    var name= document.getElementById("name").value;
    console.log('Your name is: ' + name);  
}

First, this gets the value of the "name" id, then this will log it to the console.

If you want to enhance this slightly, you can also make a few adjustments to the js to display the name in the output id tag you created. Here's how your final work might look.

 function showName(){ var name= document.getElementById("name").value; document.getElementById("output").innerText = name; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Names</title> <link type="text/css" rel="stylesheet" href="css/style.css" /> <script type="text/javascript" rel="script" src="js/scripts.js" defer></script> </head> <body> <label for="name">Your name: </label> <input type="text" id="name" name="name"> <input id="submit-button" name="submit-button" type="submit" value="Submit" onclick="showName()" /> <h3>Result</h3> <div id="output"> Form not submitted yet. </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM