How do I add DOM JavaScript to my script.js so when info(firstname, lastname, and age) is submitted, it displays on the main page as a sentence?

Viewed 37

How do I take this HTML code and display the input data below the submit button where the person div tag is using DOM in JavaScript??? I want it to display as 'Hello, (firstname)(lastname)! You are (age) old.'

<!DOCTYPE html>
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>replit</title>
   <link href="style.css" rel="stylesheet" type="text/css"/>
   <script src="script.js"></script>
 </head>
 <body>
    <div class="container">
        <form action="index.html" method="post" id="signup">
            <h1>Input Your Information</h1>       
          <div class ="info">
            <div class="field">
                <label for="firstname"></label>
                <input type="text" id="text" name="firstname" placeholder="First Name"/>
            </div>       
            <div class="field">
                <label for="lastname"></label>
                <input type="text" id="text" name="lastname" placeholder="Last Name"/>
            </div>        
      <div class="field">
                <label for="age"></label>
                <input type="text" id="text" name="age" placeholder="Age"/>
            </div>      
            <div class="field">
            <button type="submit" onclick=display() class="button">Submit</button>
            </div>      
        </div>   
          <div id="person"></div>
      </form>
  </div>
1 Answers

You can target by names or ID, meaning you should give your form a name attribute like this:

<form action="index.html" method="post" id="signup" name="frm_signup">

Then your display method will be as follows:

let display = ()=>{
  let firstname = documents.forms['frm_signup']['firstname'].value;
  let lastname= documents.forms['frm_signup']['lastname'].value;
  let age= documents.forms['frm_signup']['age'].value;
 
  document.getElementById('person').innerText = "Hello, " + firstname + " " + lastname + "! You are " + age + " old."

Though, you can still get the form even without the name by using index of 0 on the form like this; documents.forms[0]['firstname'] only if you are sure you only have 1 form on your page.

Also, if you want to use IDs, kindly make sure the id for each input is unique instead of using id="text" for all of them. Therefore, if the firstname input has id="firstname for instance, then you will get the values like this;

let firstname = documents.getElementById('firstname').value;
Related