Search code examples
javascripthtmlarraysconcatenationparagraph

How to take form information entered into an info array, and print out that array to a paragraph?


I am trying to take form information, enter them into an info array and then print out that array to a paragraph within a string concatenation.

Here's my HTML:

<body>
   <input type="text" id="name" placeholder="Enter first name">
   <input type="text" id="lName" placeholder="Enter last name">
   <input type="text" id="age" placeholder="Enter age">
   <input type="text" id="email" placeholder="Enter email address">
   <button>Add Info</button>
   <article>
      <div>
         <p>8</p>
      </div>
   </article>
   <p id="future"></p>
   <main>
</body>

Here's my Javascript:

const btn = document.querySelector('button');
const paras = document.querySelectorAll('p');

    btn.addEventListener("click", function(){
      const name = document.getElementById("#name");
      const lName = document.querySelector("#lname");
      const age = document.querySelector("#age");
      const email = document.querySelector("#email");
      let info = [name + " " + lName + " , you are " + age + "!" + " But by your next birthday, you will 
      inherit $10 million dollars! We will email you your fortune to: " + email + "."];
      document.querySelector("#future").innerHTML = info;})

I get:

null [object HTMLInputElement] , you are [object HTMLInputElement]! But by your next birthday, you will inherit $10 million dollars! We will email you your fortune to: null.


Solution

  • There are several problems:

    1. getElementById expects only the id as argument, without #. (querySelector need this, because it takes a css-selector as argument).
    2. There's a typo in this selector: const lName = document.querySelector("#lname"): #lName instead of #lname.
    3. You printed the input-elements, not their values. Use .value for that.

    const btn = document.querySelector('button');
    const paras = document.querySelectorAll('p');
    
    btn.addEventListener("click", function() {
      const name = document.getElementById("name");
      const lName = document.querySelector("#lName");
      const age = document.querySelector("#age");
      const email = document.querySelector("#email");
      let info = [name.value + " " + lName.value + " , you are " + age.value + "!" + " But by your next birthday, you will inherit $10 million dollars!We will email you your fortune to: " + email.value + "."];
      document.querySelector("#future").innerHTML = info;
    })
    <body>
      <input type="text" id="name" placeholder="Enter first name">
      <input type="text" id="lName" placeholder="Enter last name">
      <input type="text" id="age" placeholder="Enter age">
      <input type="text" id="email" placeholder="Enter email address">
      <button>Add Info</button>
    
      <article>
        <div>
          <p>8</p>
        </div>
      </article>
      <p id="future"></p>
    
    </body>