DEV Community

Cover image for How to Add User Inputs from a Form to a Card Using JavaScript
Oluwaseun Lawal
Oluwaseun Lawal

Posted on • Edited on

How to Add User Inputs from a Form to a Card Using JavaScript

Article Objective
At the end of this article, the reader will learn how to create a form and a set of cards, then how to add the inputs from the form (created with HTML and CSS) to a specific card (also created with HTML and CSS) all on a webpage using JavaScript.

Article Outline

  • Introduction
  • Prerequisites
  • Step 1: Creating a form with submit button (HTML & CSS)
  • Step 2: Creating four cards and styling them (HTML & CSS)
  • Step 3: Getting the form inputs (JavaScript)
  • Step 4: Adding the form inputs to the empty card (JavaScript)
  • Conclusion

Prerequisites

  • Have VS Code installed
  • Set up a project folder

Introduction

Forms can be created for different purposes on a website or blog. For instance, a form can be created to enable a user to subscribe to an online service or to submit a complaint on a website. Also, a form can be created to get feedback from the user of a website. So, whatever a form is meant to achieve is determined by the owner(s) of a website.

In this technical article, we are going to create a form that accepts user inputs; the form will have up to seven input fields in which a user can enter a laptop brand and their desired specifications. Thereafter, we will create a set of four cards listing laptop brands and their specifications. The first, second, and third cards are going to be pre-filled with specifications while the fourth card remains empty (input will come from the user).

Now using JavaScript, at the click of the “Submit” button, the user input from the form we created is then added to the empty card so that it looks like the other three cards. All of these are quite straightforward to achieve by following the steps I have outlined in this article.

Without further long talks, let’s get started.

Note: If you are just starting out learning HTML and CSS, follow Step 1 and Step 2 closely on how to create a form and a set of cards, respectively.
If you are already familiar with how to create a form and a set of cards using HTML and CSS, you can jump to Step 3 and continue.


Step 1: Creating a form with submit button (HTML & CSS)

The first thing we have to do is to open up our code editor (VS Code is used here) and create three separate files, which are:

  • index.html
  • style.css
  • script.js

We then get started under HTML by entering Shift + ! or inputting html5 and hitting enter to load up the default HTML codes. The next thing to do is to link the other two files (i.e., CSS and JavaScript) to our HTML file. The following explains better.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Input to a Card</title>

    <link rel="stylesheet" href="/style.css">

    <script defer src="/script.js"></script>
</head>
Enter fullscreen mode Exit fullscreen mode

Note: ‘defer’ used in the JavaScript link is to tell the server to first load HTML and CSS files before executing JavaScript.

We proceed to create the form (using a form object in HTML) inside a container, and it will have the following inputs: a header, Laptop name, Processor, Generation, RAM, SSD, Screen size, and Backup.

 <div class="form-container">

        <h3>Laptop brand specifications</h3> <br> <br>

        <form action="">
            <input type="text" placeholder="Laptop name" class="laptop-name"> <br> <br>
            <input type="text" placeholder="Processor" class="laptop-processor"> <br> <br>
            <input type="text" placeholder="Generation" class="laptop-gen"> <br> <br>
            <input type="text" placeholder="RAM" class="laptop-ram"> <br> <br>
            <input type="text" placeholder="SSD" class="laptop-ssd"> <br> <br>
            <input type="text" placeholder="Screen size" class="laptop-screensize"> <br> <br>
            <input type="text" placeholder="Backup" class="laptop-backup"> <br> <br>

            <button class="btn" type="submit" onclick="submitBtn()">Submit</button>

        </form>

    </div>
Enter fullscreen mode Exit fullscreen mode

In order to style the form and be able to access each of the input fields in JavaScript, we have to use a selector (class name) – as the screenshot above shows – for each of the input fields. The selectors can now be used to style the form in CSS:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    text-decoration: none;
    list-style: none;
}


body
{
    background-color: rgb(196, 248, 255);
}

.form-container
{
    border: 2px groove;
    width: 230px;
    height: 400px;
    padding: 20px;
    border-radius: 5px;
    margin: 10px;
    background-color: azure;
}


form input{
    border: none;
    border-bottom:1px solid black ;
    background: none;
}

input:focus{
    outline: none;
}

.btn
{
    width: 80px;
    height: 25px;
    font-size: 15px;
    background-color: blue;
    color: white;
    border-radius: 5px;
    border-color: white;
}
Enter fullscreen mode Exit fullscreen mode

The form will appear as follows:

Form image

We are done with creating the form, and we proceed to the next step.


Step 2: Creating four cards and styling them (HTML & CSS)

Here, we are going to create four cards, which will all have laptop brand specifications, out of which three of them will be pre-filled and the remaining one left blank. The four cards are each going to have the following selectors: card1, card2, card3, and output and be placed inside a parent container, which is going to have the selector specs-container. Each of the four cards is going to have a different image and similar styling (though with different background colors).

Here are the HTML codes to create the cards:

<section class="specs-container">

        <div class="specs-card">
            <img src="/Dell laptop.jpg" class="laptop-image" alt="">

            <ul class="specs-list">
                <li><b>Laptop name</b>: Dell</li>
                <li><b>Processor</b>: Intel Core i7</li>
                <li><b>Generation</b>: 8th</li>
                <li><b>RAM</b>: 16GB</li>
                <li><b>SSD</b>: 512GB</li>
                <li><b>Screen size</b>: 15.6 inches</li>
                <li><b>Backup</b>: 7 hours</li>
            </ul>
        </div>

        <div class="specs-card">
            <img src="/hp-laptop.jpg" class="laptop-image" alt="">

            <ul class="specs-list">
                <li><b>Laptop name</b>: HP</li>
                <li><b>Processor</b>: Intel Core i5</li>
                <li><b>Generation</b>: 10th</li>
                <li><b>RAM</b>: 16GB</li>
                <li><b>SSD</b>: 512GB</li>
                <li><b>Screen size</b>: 14.1 inches</li>
                <li><b>Backup</b>: 9 hours</li>
            </ul>
        </div>

        <div class="specs-card">
            <img src="/Lenovo laptop.webp" class="laptop-image" alt="">

            <ul class="specs-list">
                <li><b>Laptop name</b>: Lenovo</li>
                <li><b>Processor</b>: Intel Core i7</li>
                <li><b>Generation</b>: 10th</li>
                <li><b>RAM</b>: 32GB</li>
                <li><b>SSD</b>: 512GB</li>
                <li><b>Screen size</b>: 13.3 inches</li>
                <li><b>Backup</b>: 10 hours</li>
            </ul>
        </div>

        <div class="output">
            <img src="/Laptop.jpg" class="laptop-image" alt="">

            <div class="specs-list">
                <p><b>Laptop name</b>: <span id="output1"></span> </p>
                <p><b>Processor</b>: <span id="output2"></span> </p>
                <p><b>Generation</b>: <span id="output3"></span> </p>
                <p><b>RAM</b>: <span id="output4"></span> </p>
                <p><b>SSD</b>: <span id="output5"></span> </p>
                <p><b>Screensize</b>: <span id="output6"></span> </p>
                <p><b>Backup</b>: <span id="output7"></span> </p>
            </div>            
        </div>
    </section>
Enter fullscreen mode Exit fullscreen mode

In order to style these cards, we will apply the following CSS:

.specs-container
{
    width: fit-content;
    height: 300px;
    margin: auto;
    padding: 10px;
    background-color: blue;
    display: flex;
    padding-top: 7.5px;
    gap: 10px;
}

.specs-card
{
    width: 250px;
    height: 285px;
    background-color: rgb(231, 231, 201);
    border-radius: 7px;

}

.laptop-image
{
    height: 140px;
    width: 250px;
    border-bottom: solid rgb(109, 216, 55);
    border-radius: 7px;
}

.specs-list
{
    padding: 5px;
}

.output
{
    width: 250px;
    height: 285px;
    background-color: rgb(253, 206, 220);
    border-radius: 7px;
}
Enter fullscreen mode Exit fullscreen mode

Now after applying all these CSS styles, the cards should finally look like this:

Form and cards

Note: The laptop images displayed in the cards do not represent the real laptops with those specifications.

As you can see, the empty card is only having labels, and there are no specifications indicated — which is because we want the specifications to come from the user via the form we created. But in order to transmit the user inputs in the form to the empty card, we need JavaScript, and this leads us to the next step.


Step 3: Getting the form inputs (JavaScript)

Before the inputs of the form can be transmitted and displayed in the empty card, we need to write a function in JavaScript with the name we specified in the submit button's onclick function in HTML, that is, submitBtn().

<button class="btn" type="submit" onclick="submitBtn()">Submit</button>
Enter fullscreen mode Exit fullscreen mode

Then we need to get the actual value of each input in the form using their selector (class name) and adding .value in JavaScript. Since we will be using the class name of each input, we have to use document.querySelector.

Here are the JavaScript codes to get the form input:

function submitBtn()
{
    var nameoflaptop = document.querySelector('.laptop-name').value;
    var processoroflaptop = document.querySelector('.laptop-processor').value;
    var genoflaptop = document.querySelector('.laptop-gen').value;
    var ramoflaptop = document.querySelector('.laptop-ram').value;
    var ssdoflaptop = document.querySelector('.laptop-ssd').value;
    var screenoflaptop = document.querySelector('.laptop-screensize').value;
    var backupoflaptop = document.querySelector('.laptop-backup').value;
}
Enter fullscreen mode Exit fullscreen mode

With this, we can get the actual value of whatever specifications a user enters into the form for the laptop name, processor, generation, RAM, SSD, screen size, and backup. But when the user clicks the submit button, nothing is going to happen – all the inputs will remain on the form. This is because at the click of the submit button, the form inputs go nowhere since we haven’t specified where they should go.

Specifying where the form inputs should go is what we will treat in the next step.


Step 4: Adding the form inputs to the empty card (JavaScript)

To be able to transmit the form inputs to the empty card, we need to get the exact location of the specification that matches the form input using JavaScript. This means the output on the card must match the input from the form.

For us to get the actual value of each output in the empty card, we use their selector (id), and to do that, we have to use document.getElementbyId. To access the individual content in the card, we say .textcontent and to finally transmit each form input to the output, we equate the output to the corresponding input.

Here are the JavaScript codes to transmit the form inputs to the outputs in the empty card:

function submitBtn()
{
    var nameoflaptop = document.querySelector('.laptop-name').value;
    var processoroflaptop = document.querySelector('.laptop-processor').value;
    var genoflaptop = document.querySelector('.laptop-gen').value;
    var ramoflaptop = document.querySelector('.laptop-ram').value;
    var ssdoflaptop = document.querySelector('.laptop-ssd').value;
    var screenoflaptop = document.querySelector('.laptop-screensize').value;
    var backupoflaptop = document.querySelector('.laptop-backup').value;


    document.getElementById("output1").textContent = nameoflaptop;
    document.getElementById("output2").textContent = processoroflaptop;
    document.getElementById("output3").textContent = genoflaptop;
    document.getElementById("output4").textContent = ramoflaptop;
    document.getElementById("output5").textContent = ssdoflaptop;
    document.getElementById("output6").textContent = screenoflaptop;
    document.getElementById("output7").textContent = backupoflaptop;

}
Enter fullscreen mode Exit fullscreen mode

Now with this, anything a user enters into each of the form inputs will go to the corresponding output on the card.

But there is a little problem here. The problem is that the webpage will automatically refresh itself at the click of the submit button, meaning that all the form inputs will show briefly on the card before the webpage gets refreshed.

By default, the submit button refreshes a webpage. But in order to prevent this from happening, we need to write a JavaScript code that prevents the submit button from refreshing the webpage, which will then allow the form inputs to be transmitted to the empty card.

const btn = document.querySelector('.btn');

btn.addEventListener('click', function handleClick(event)
{
    event.preventDefault();
    const inputtexts = document.querySelectorAll('.laptop-name, .laptop-processor, .laptop-gen, .laptop-ram');
    const input_texts = document.querySelectorAll('.laptop-ssd, .laptop-screensize, .laptop-backup');

    inputtexts.forEach(input => {
        input.value = '';
    });

    input_texts.forEach(input => {
        input.value = '';
    });
});
Enter fullscreen mode Exit fullscreen mode

So, with this, the form inputs should be transmitted to the empty card without the webpage being refreshed automatically.

User inputs in form

User inputs showing on empty card

As you can see from the second screenshot, all the input fields in the form got cleared after the submit button was clicked and the inputs transmitted to the empty card. This is because in the code above, the following was specified:

inputtexts.forEach(input => {
        input.value = '';
    });

    input_texts.forEach(input => {
        input.value = '';
    });
Enter fullscreen mode Exit fullscreen mode

What this code does is to return each of the input fields in the form to null after the submit button is clicked.

Below are the code implementations for this project on my CodePen.

Note: The laptop image for each card is not showing due to issues with uploading images on Codepen.

Conclusion
In this technical article, we have been able to learn about how to add user inputs from a form to a card using JavaScript. The steps taken to achieve this are pretty straightforward, and it is easy to implement on a webpage. The card that was used here to display the form inputs is the example I chose; actually, you can transmit the inputs from a form to any part of your webpage. So if you are looking to build a website with a form that accepts inputs and transmit it to a card (or somewhere on your webpage), you won’t go wrong following the steps above.

Top comments (0)