How to Create Form Fields Dynamically with JavaScript

Faraz

By Faraz -

Learn to create dynamic form fields with JavaScript in this step-by-step tutorial for beginners. Discover how to add and remove form fields dynamically.


dynamic-field.png

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Forms are an integral part of many websites. They are used to gather user information, feedback, and more. With JavaScript, it is possible to create form fields dynamically, allowing developers to add, remove, and manipulate form elements in real-time. This can be particularly useful for users who need to input multiple pieces of information, as well as for developers who want to create more dynamic and interactive forms.

In this article, we will explore the process of creating form fields dynamically with JavaScript. We will cover the basics of creating form elements and manipulating them with JavaScript, as well as some more advanced techniques for making your forms even more dynamic and engaging.

To create Fields dynamically using JavaScript, we can use the document.createElement method to create the element. Then we can use the setAttribute method to set the element attributes and finally we can use the appendChild method to append the elements into the parent element.

Let's start making these amazing responsive dynamic form fields Using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

The first thing we need to do is create our HTML File. I've only included three fields, two of them (Name and Email) are static and I make another Field dynamic, on which we will be performing the actions.

After creating the files just paste the below HTML codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Here's an explanation of the HTML code:

1. Document Type Declaration

<!DOCTYPE html>
<html>
  • <!DOCTYPE html>: Declares the document to be HTML5.
  • <html>: Root element of the HTML document.

2. Head Section

<head>
  <title>Dynamic Fields</title>
  <link rel="stylesheet" type="text/css" href="styles.css" />
  <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
  • <title>Dynamic Fields</title>: Sets the title of the web page to "Dynamic Fields".
  • <link rel="stylesheet" type="text/css" href="styles.css" />: Links an external CSS file named "styles.css" for styling the page.
  • <link rel="stylesheet" type="text/css" href="https://stackpath....me.min.css" />: Links an external CSS file from Font Awesome for using icons.

3. Body Section

<body>
  <h1>codewithFaraz</h1>
  <div class="container">
    <form action="" method="POST">
      <div id="formfield">
        <input type="text" name="text" class="text" size="50" placeholder="Name" required>
        <input type="text" name="text" class="text" size="50" placeholder="Email" required>
        <input type="text" name="text" class="text" size="50" placeholder="Optional Field">
      </div>
      <input name="submit" type="Submit" value="Submit">
    </form>
    <div class="controls">
      <button class="add" onclick="add()"><i class="fa fa-plus"></i>Add</button>
      <button class="remove" onclick="remove()"><i class="fa fa-minus"></i>Remove</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Body Elements

  • <h1>codewithFaraz</h1>: An h1 heading displaying "codewithFaraz".

Container Div

<div class="container">
  • <div class="container">: A container div for grouping the form and control buttons.

Form Element

<form action="" method="POST">
  <div id="formfield">
    <input type="text" name="text" class="text" size="50" placeholder="Name" required>
    <input type="text" name="text" class="text" size="50" placeholder="Email" required>
    <input type="text" name="text" class="text" size="50" placeholder="Optional Field">
  </div>
  <input name="submit" type="Submit" value="Submit">
</form>
  • <form action="" method="POST">: A form element with the POST method. The action attribute is empty, meaning the form will submit to the same page.
  • <div id="formfield">: A div with an ID of "formfield" containing the input fields.
  • <input type="text" name="text" class="text" size="50" placeholder="Name" required>: A text input field for "Name" with a placeholder and required attribute.
  • <input type="text" name="text" class="text" size="50" placeholder="Email" required>: A text input field for "Email" with a placeholder and required attribute.
  • <input type="text" name="text" class="text" size="50" placeholder="Optional Field">: A text input field for an optional field with a placeholder.
  • <input name="submit" type="Submit" value="Submit">: A submit button for the form.

Control Buttons

<div class="controls">
  <button class="add" onclick="add()"><i class="fa fa-plus"></i>Add</button>
  <button class="remove" onclick="remove()"><i class="fa fa-minus"></i>Remove</button>
</div>
  • <div class="controls">: A div containing the control buttons.
  • <button class="add" onclick="add()"><i class="fa fa-plus"></i>Add</button>: A button with the class "add" that calls the add() function on click. It contains an icon (Font Awesome "plus" icon) and the text "Add".
  • <button class="remove" onclick="remove()"><i class="fa fa-minus"></i>Remove</button>: A button with the class "remove" that calls the remove() function on click. It contains an icon (Font Awesome "minus" icon) and the text "Remove".

JavaScript

<script src="script.js"></script>
  • <script src="script.js"></script>: Links an external JavaScript file named "script.js" for adding interactivity, such as the add() and remove() functions mentioned in the button onclick attributes.

This is the basic structure of our dynamically form fields using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the form fields is in place, the next step is to add styling to the form fields using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.

Next, we will create our CSS file. In this file, we'll style the form fields with CSS to make them look more presentable. This can include things like setting widths and heights, adding borders, and changing the font.

Here's an explanation of the CSS code:

1. Body Styling

body {
  background-color: #c1cce0;
  font-family: 'Jost', sans-serif;
  color: #fff;
}
  • background-color: #c1cce0: Sets the background color to a light blue-gray.
  • font-family: 'Jost', sans-serif: Uses the 'Jost' font and falls back to a sans-serif font if 'Jost' is unavailable.
  • color: #fff: Sets the text color to white.

2. Heading Styling

h1 {
  text-align: center;
  font-size: 48px;
  color: #232c3d;
}
  • text-align: center: Centers the heading text.
  • font-size: 48px: Sets the font size to 48 pixels.
  • color: #232c3d: Sets the text color to a dark blue-gray.

3. Container Styling

.container {
  width: 400px;
  margin: 40px auto;
  padding: 10px;
  border-radius: 5px;
  background: white;
  box-shadow: 0px 10px 40px 0px rgba(47, 47, 47, 0.1);
}
  • width: 400px: Sets the width to 400 pixels.
  • margin: 40px auto: Centers the container horizontally with a 40-pixel margin on top and bottom.
  • padding: 10px: Adds 10 pixels of padding inside the container.
  • border-radius: 5px: Rounds the corners with a 5-pixel radius.
  • background: white: Sets the background color to white.
  • box-shadow: 0px 10px 40px 0px rgba(47, 47, 47, 0.1): Adds a shadow around the container.

4. Text Input Styling

input[type="text"] {
  padding: 10px;
  margin: 10px auto;
  display: block;
  border-radius: 5px;
  border: 1px solid lightgrey;
  background: none;
  width: 274px;
  color: black;
}
  • padding: 10px: Adds 10 pixels of padding inside the text input.
  • margin: 10px auto: Centers the input horizontally with a 10-pixel margin on top and bottom.
  • display: block: Makes the input a block-level element.
  • border-radius: 5px: Rounds the corners with a 5-pixel radius.
  • border: 1px solid lightgrey: Sets a 1-pixel solid light gray border.
  • background: none: Sets no background.
  • width: 274px: Sets the width to 274 pixels.
  • color: black: Sets the text color to black.
input[type="text"]:focus {
  outline: none;
}
  • outline: none: Removes the default outline when the text input is focused.

5. Submit Button Styling

input[type="Submit"] {
  margin: 10px auto;
  display: block;
  width: 40%;
  height: 40px;
  border: 1px solid;
  border-radius: 25px;
  font-size: 18px;
  cursor: pointer;
}
  • margin: 10px auto: Centers the button horizontally with a 10-pixel margin on top and bottom.
  • display: block: Makes the button a block-level element.
  • width: 40%: Sets the width to 40% of the parent element.
  • height: 40px: Sets the height to 40 pixels.
  • border: 1px solid: Sets a 1-pixel solid border.
  • border-radius: 25px: Rounds the corners with a 25-pixel radius.
  • font-size: 18px: Sets the font size to 18 pixels.
  • cursor: pointer: Changes the cursor to a pointer on hover.
input[type="Submit"]:hover {
  background: #2691d9;
  color: #e9f4fb;
  transition: 0.5s;
}
  • background: #2691d9: Changes the background color to blue on hover.
  • color: #e9f4fb: Changes the text color to a light blue on hover.
  • transition: 0.5s: Adds a transition effect of 0.5 seconds.

6. Controls Styling

.controls {
  width: 294px;
  margin: 15px auto;
}
  • width: 294px: Sets the width to 294 pixels.
  • margin: 15px auto: Centers the controls horizontally with a 15-pixel margin on top and bottom.

7. Add and Remove Buttons Styling

.add {
  padding: 5px;
  border: 1px solid;
  border-radius: 25px;
  cursor: pointer;
}
  • padding: 5px: Adds 5 pixels of padding inside the add button.
  • border: 1px solid: Sets a 1-pixel solid border.
  • border-radius: 25px: Rounds the corners with a 25-pixel radius.
  • cursor: pointer: Changes the cursor to a pointer on hover.
.remove {
  float: right;
  padding: 5px;
  border: 1px solid;
  border-radius: 25px;
  cursor: pointer;
}
  • float: right: Floats the remove button to the right.
  • padding: 5px: Adds 5 pixels of padding inside the remove button.
  • border: 1px solid: Sets a 1-pixel solid border.
  • border-radius: 25px: Rounds the corners with a 25-pixel radius.
  • cursor: pointer: Changes the cursor to a pointer on hover.

8. Button Icon Margin

.controls button i {
  margin-right: 5px;
}
  • margin-right: 5px: Adds a 5-pixel right margin to icons inside buttons.

9. Hover Effects for Add and Remove Buttons

.remove:hover, .add:hover {
  background: #2691d9;
  color: #e9f4fb;
  transition: 0.5s;
}
  • background: #2691d9: Changes the background color to blue on hover.
  • color: #e9f4fb: Changes the text color to a light blue on hover.
  • transition: 0.5s: Adds a transition effect of 0.5 seconds.

This will give our dynamic form fields an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  background-color: #c1cce0;
  font-family: 'Jost',sans-serif;
  color: #fff;
}
h1 {
  text-align: center;
  font-size: 48px;
  color: #232c3d;
}

.container {
  width: 400px;
  margin: 40px auto;
  padding: 10px;
  border-radius: 5px;
  background: white;
  box-shadow: 0px 10px 40px 0px rgba(47,47,47,.1);
}

input[type="text"]{
  padding: 10px;
  margin: 10px auto;
  display: block;
  border-radius: 5px;
  border: 1px solid lightgrey;
  background: none;
  width: 274px;
  color: black;
}

input[type="text"]:focus {
  outline: none;
}

input[type="Submit"]{
  margin: 10px auto;
  display: block;
  width: 40%;
  height: 40px;
  border: 1px solid;
  border-radius: 25px;
  font-size: 18px;
  cursor: pointer;
}

input[type="Submit"]:hover{
  background: #2691d9;
  color: #e9f4fb;
  transition: .5s;
}

.controls {
  width: 294px;
  margin: 15px auto;
}

.add {
  padding: 5px;
  border: 1px solid;
  border-radius: 25px;
  cursor: pointer;
}

.remove {
  float: right;
  padding: 5px;
  border: 1px solid;
  border-radius: 25px;
  cursor: pointer;
}
.controls button i{
  margin-right: 5px;
}

.remove:hover, .add:hover{
  background: #2691d9;
  color: #e9f4fb;
  transition: .5s;
} 

Step 3 (JavaScript Code):

The final step in creating dynamic form fields using HTML, CSS, and JavaScript is to add and remove form fields dynamically using JavaScript. JavaScript allows us to create dynamic and interactive elements on the website.

Adding form fields with JavaScript is a straightforward process. First, you need to create a new form field element using the document.createElement method. Next, you need to set the properties of this element, such as its type, name, and value. Finally, you need to add the element to your form using the appendChild method.

Removing form fields with JavaScript is just as easy as adding them. To remove a form field, you simply need to find the element you want to remove and use the removeChild method to remove it from the form.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

Frequently Asked Question (FAQ)

1. What is the purpose of creating form fields dynamically with JavaScript? The purpose of creating form fields dynamically with JavaScript is to add, remove, and modify form elements in real-time, allowing you to create more dynamic and interactive forms that better meet the needs of your users.

2. How do I add form fields with JavaScript? To add form fields with JavaScript, you need to create a new form field element using the document.createElement method, set the properties of this element, such as its type, name, and value, and then add the element to your form using the appendChild method.

3. How do I remove form fields with JavaScript? To remove form fields with JavaScript, you need to find the element you want to remove and use the removeChild method to remove it from the form.

4. What are some advanced techniques for dynamic form creation with JavaScript? Some advanced techniques for dynamic form creation with JavaScript include using JavaScript events to trigger changes in your form fields, validating user input, and creating custom form fields, such as dropdown menus, checkboxes, and radio buttons.

var formfield = document.getElementById('formfield');

function add(){
  var newField = document.createElement('input');
  newField.setAttribute('type','text');
  newField.setAttribute('name','text');
  newField.setAttribute('class','text');
  newField.setAttribute('siz',50);
  newField.setAttribute('placeholder','Optional Field');
  formfield.appendChild(newField);
}

function remove(){
  var input_tags = formfield.getElementsByTagName('input');
  if(input_tags.length > 2) {
    formfield.removeChild(input_tags[(input_tags.length) - 1]);
  }
}

Final Output:

dynamic-field.gif

Conclusion:

In conclusion, creating form fields dynamically with JavaScript is a powerful tool that can greatly enhance the functionality and user experience of your forms. With the right tools and techniques, you can create forms that are more dynamic, interactive, and tailored to the specific needs of your users. Whether you are a seasoned developer or just starting out, we hope this article has provided you with the knowledge and inspiration you need to create amazing forms with JavaScript.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺