Create Car Registration System Using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a simple car registration system with HTML, CSS, and JavaScript in this easy step-by-step guide. Build a functional and attractive form with minimal code.


create-car-registration-system-using-html-css-and-javascript.webp

Table of Contents

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

Are you looking to create a car registration system using HTML, CSS, and JavaScript? You’ve come to the right place! In this tutorial, we will guide you through the process of building a simple car registration form that collects user information and validates the input using JavaScript. This system can be a great starting point for more complex applications. Let’s get started!

Prerequisites:

Before we dive into the code, make sure you have the following:

  1. Basic knowledge of HTML – Understanding how to create basic web pages and elements.
  2. CSS basics – Knowing how to style web pages to make them look appealing.
  3. JavaScript fundamentals – Familiarity with functions, events, and basic form validation.

Source Code

Step 1 (HTML Code):

We’ll begin by creating the basic HTML structure for our car registration form. This includes input fields for the car owner’s details, like name, email, car model, and license plate.

Let's break down the HTML code step by step:

1. <!DOCTYPE html>

  • Declares the document type as HTML5.

2. <html lang="en">

  • Specifies the language of the document as English.

3. <head> Section

Contains metadata and links to stylesheets:

  • <meta charset="UTF-8">: Specifies the character encoding as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive on all devices.
  • <title>: Sets the page title as "Car Registration System".
  • <link rel="stylesheet" href="...">: Includes two stylesheets:
    • Google Fonts (Poppins font family).
    • styles.css for custom styling.

4. <body> Section

This is the main content area of the page.

a. Main Container (<div class="main-container">)

Encapsulates the entire content.

b. Header (<h1>Car Registration System</h1>)

  • Displays the main title of the application.

c. Tabs (<div class="tabs">)

  • Provides navigation between two sections:
    1. Register Car
    2. View All Registrations
  • Each tab is a <button> element with:
    • A data-tab attribute to identify its target section.
    • An active class on the first button to highlight the default active tab.

d. Tab Content Sections

i. Register Car (<div class="tab-content" id="register">)
  • Contains a form for registering a new car.
  • <form>: Encapsulates input fields.
    • Fields include:
      • Owner's Name (<input type="text" id="ownerName" ...>).
      • Car Model (<input type="text" id="carModel" ...>).
      • License Number (<input type="text" id="licenseNumber" ...>).
      • Registration Date (<input type="date" id="registrationDate" ...>).
    • Submit Button: Saves the entered data.
ii. View All Registrations (<div class="tab-content" id="view">)
  • Contains a table to display all registered cars.
  • Table (<table id="registrationTable">):
    • <thead>: Table headers.
    • <tbody>: Empty section where rows will be dynamically added via JavaScript.

e. External JavaScript (<script src="script.js">)

  • Links to a JavaScript file (script.js) for functionality, like:
    • Tab switching.
    • Handling form submissions.
    • Dynamically updating the table.

Step 2 (CSS Code):

Now, we’ll add some simple CSS to make the form look more appealing. You can create a separate CSS file named styles.css.

Here's an explanation of the key parts:

1. body

  • Font Family: Sets the font of the entire page to 'Poppins' (imported from Google Fonts).
  • Margin: Removes the default margin from the page.
  • Padding: Adds 20px padding around the page's content.
  • Background Color: Sets the background color of the page to a light grayish color (#f8f9fa).

2. h1

  • Text Alignment: Centers the header text.
  • Color: Sets the text color to a dark gray (#333).

3. .tabs

  • Display: Uses Flexbox (display: flex) to lay out the tab buttons in a row.
  • Justify Content: Centers the buttons horizontally within the parent container.
  • Margin Bottom: Adds a 20px space below the tabs.

4. .tab-button

  • Font Family: Inherits the font family set for the body.
  • Padding: Adds 10px top/bottom and 20px left/right padding to the buttons.
  • Border: Removes the default border.
  • Background Color: Sets the initial background color of the buttons to a light gray (#ddd).
  • Text Color: Sets the text color to dark gray (#333).
  • Cursor: Changes the cursor to a pointer when hovering over the buttons.
  • Font Size: Sets the font size to 16px.
  • Transition: Adds a smooth 0.3-second transition for background color changes.
  • Border Radius: Rounds the top corners of the buttons (5px 5px 0 0).
  • Margin: Adds 5px of horizontal spacing between buttons.

5. .tab-button.active

  • Active Tab Styles: When a tab button has the active class:
    • Background Color: Changes the background color to blue (#007bff).
    • Text Color: Changes the text color to white (#fff).

6. .tab-content

  • Display: Initially hides the tab content (display: none).
  • Animation: Applies a fade-in effect when the content becomes visible (defined below).

7. .tab-content.active

  • Display: When the active class is added to the tab content, it becomes visible (display: block).

8. .card

  • Background: Sets the background color to white (#fff).
  • Padding: Adds 20px padding inside the card.
  • Margin: Centers the card horizontally with auto margins.
  • Border Radius: Rounds the corners of the card with a 10px radius.
  • Box Shadow: Adds a subtle shadow around the card for a 3D effect.
  • Max Width: Limits the card's width to 650px.

9. .form-group

  • Margin Bottom: Adds 15px of space below each form group (i.e., each input field and its label).

10. label

  • Display: Makes the label a block element (so it occupies the full width).
  • Font Weight: Sets the font weight to bold.
  • Margin Bottom: Adds 5px space below each label.

11. input

  • Font Family: Inherits the font from the body.
  • Width: Sets the width to 90% of the parent container.
  • Padding: Adds 10px padding inside each input.
  • Border: Sets a light gray border (#ccc).
  • Border Radius: Rounds the input's corners by 5px.

12. button

  • Background Color: Sets the background color to green (#28a745).
  • Text Color: Sets the text color to white (#fff).
  • Border: Removes the default border.
  • Padding: Adds 10px top/bottom and 20px left/right padding.
  • Border Radius: Rounds the button's corners by 5px.
  • Cursor: Changes the cursor to a pointer when hovering over the button.
  • Transition: Adds a 0.3-second smooth transition for background color changes.

13. button:hover

  • Background Color: Changes the background color to a darker shade of green (#218838) when the button is hovered over.

14. table

  • Width: Sets the table's width to 100% of the parent container.
  • Border Collapse: Ensures that table borders collapse into a single line.
  • Margin Top: Adds a 20px margin above the table.

15. th, td

  • Padding: Adds 10px padding inside both table headers (<th>) and table cells (<td>).
  • Text Alignment: Aligns the text to the left in both headers and cells.
  • Border Bottom: Adds a light gray border beneath each row.

16. th

  • Background Color: Sets the background color of the table headers to a light gray (#f8f9fa).

17. .edit-btn, .delete-btn

  • Font Family: Inherits the font family from the body.
  • Padding: Adds 5px top/bottom and 10px left/right padding.
  • Margin: Adds 2px of spacing between the buttons.
  • Border: Removes the default border.
  • Border Radius: Rounds the button corners by 5px.
  • Cursor: Changes the cursor to a pointer when hovering over the buttons.
  • Text Color: Sets the text color to white (#fff).

18. .edit-btn

  • Background Color: Sets the background color of the "Edit" button to yellow (#ffc107).

19. .delete-btn

  • Background Color: Sets the background color of the "Delete" button to red (#dc3545).

20. Animations - @keyframes fadeIn

  • Fade-in Effect: Defines the fadeIn animation that smoothly transitions the element's opacity from 0 (invisible) to 1 (fully visible) over 0.3 seconds.
body {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 20px;
  background-color: #f8f9fa;
}

h1 {
  text-align: center;
  color: #333;
}

/* Tabs */
.tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.tab-button {
  font-family: inherit;
  padding: 10px 20px;
  border: none;
  background-color: #ddd;
  color: #333;
  cursor: pointer;
  font-size: 16px;
  transition: 0.3s ease;
  border-radius: 5px 5px 0 0;
  margin: 0 5px;
}

.tab-button.active {
  background-color: #007bff;
  color: #fff;
}

/* Tab Content */
.tab-content {
  display: none;
  animation: fadeIn 0.3s;
}

.tab-content.active {
  display: block;
}

/* Card */
.card {
  background: #fff;
  padding: 20px;
  margin: auto;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  max-width: 650px;
}

/* Form Styles */
.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

input {
  font-family: inherit;
  width: 90%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  background-color: #28a745;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #218838;
}

/* Table Styles */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f8f9fa;
}

.edit-btn, .delete-btn {
  font-family: inherit;
  padding: 5px 10px;
  margin: 2px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  color: #fff;
}

.edit-btn {
  background-color: #ffc107;
}

.delete-btn {
  background-color: #dc3545;
}

/* Animations */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
} 

Step 3 (JavaScript Code):

The final step is to add JavaScript functionality to validate the form and handle the form submission. We’ll create a script file named script.js to handle this.

Here's a breakdown of the main sections:

Tab Switching Logic

  1. Event Listener for Tab Buttons:
    • document.querySelectorAll('.tab-button').forEach((button) => {...}: Adds a click event listener to each tab button.
    • On click, the code retrieves the data-tab attribute of the clicked button to identify which tab content should be displayed.
    • It then updates the active tab button by removing the active class from all buttons and adding it to the clicked button.
    • Similarly, it updates the active tab content by removing the active class from all content sections and adding it to the content corresponding to the clicked tab.

Registration Form Logic

  1. Initial Setup:
    • The code listens for the DOMContentLoaded event, which ensures that the page has loaded before calling loadRegistrations(). This function retrieves saved registrations from local storage and displays them in the table.
  2. Form Handling:
    • The form is the registration form element, and registrationTable is the table where registrations will be displayed.
    • editIndex is a variable used to track the index of a registration being edited.
  3. Loading Registrations:
    • loadRegistrations(): This function retrieves the saved registrations from local storage, parses them from JSON format, and passes them to the displayRegistrations function to show them in the table.
  4. Saving or Editing Registration:
    • saveRegistration(): This function saves a new or updated registration.
      • If editIndex is not null, it updates the existing registration at that index.
      • Otherwise, it adds a new registration.
    • After saving, it reloads the registrations from local storage and updates the displayed table.
  5. Deleting a Registration:
    • deleteRegistration(index): This function removes a registration at the specified index from the local storage and updates the displayed table.
  6. Displaying Registrations:
    • displayRegistrations(): This function takes the list of registrations and dynamically generates HTML table rows for each registration, inserting them into the table body. It also includes "Edit" and "Delete" buttons for each entry, which call the respective functions when clicked.
  7. Form Submission:
    • When the form is submitted, the code prevents the default behavior (page reload) with e.preventDefault().
    • It then checks if all required fields (ownerName, carModel, licenseNumber, registrationDate) are filled out. If any field is missing, an alert is shown, and the form submission is stopped.
    • If all fields are valid, the registration is saved via saveRegistration(), and the form is reset.
  8. Editing a Registration:
    • editRegistration(index): This function populates the form with the values of the selected registration (using the provided index). It also sets the editIndex so that when the form is submitted, it updates the existing registration instead of adding a new one.
document.querySelectorAll('.tab-button').forEach((button) => {
    button.addEventListener('click', () => {
      const tab = button.getAttribute('data-tab');
  
      // Update active tab button
      document.querySelectorAll('.tab-button').forEach((btn) => btn.classList.remove('active'));
      button.classList.add('active');
  
      // Update active tab content
      document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active'));
      document.getElementById(tab).classList.add('active');
    });
  });
  
  // Registration Form Logic
  document.addEventListener('DOMContentLoaded', () => {
    loadRegistrations(); // Load saved registrations on page load
  });
  
  const form = document.getElementById('registrationForm');
  const registrationTable = document.getElementById('registrationTable');
  let editIndex = null;
  
  // Load registrations from local storage
  function loadRegistrations() {
    const registrations = JSON.parse(localStorage.getItem('registrations')) || [];
    displayRegistrations(registrations);
  }
  
  // Save new or updated registration to local storage
  function saveRegistration(registration) {
    let registrations = JSON.parse(localStorage.getItem('registrations')) || [];
    if (editIndex !== null) {
      registrations[editIndex] = registration;
      editIndex = null;
    } else {
      registrations.push(registration);
    }
    localStorage.setItem('registrations', JSON.stringify(registrations));
    loadRegistrations();
  }
  
  // Delete a registration
  function deleteRegistration(index) {
    let registrations = JSON.parse(localStorage.getItem('registrations')) || [];
    registrations.splice(index, 1);
    localStorage.setItem('registrations', JSON.stringify(registrations));
    loadRegistrations();
  }
  
  // Display registrations in the table
  function displayRegistrations(registrations) {
    const tableBody = registrationTable.querySelector('tbody');
    tableBody.innerHTML = '';
    registrations.forEach((registration, index) => {
      const row = `
        <tr>
          <td>${registration.ownerName}</td>
          <td>${registration.carModel}</td>
          <td>${registration.licenseNumber}</td>
          <td>${registration.registrationDate}</td>
          <td>
            <button class="edit-btn" onclick="editRegistration(${index})">Edit</button>
            <button class="delete-btn" onclick="deleteRegistration(${index})">Delete</button>
          </td>
        </tr>
      `;
      tableBody.insertAdjacentHTML('beforeend', row);
    });
  }
  
  // Handle form submission
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const registration = {
      ownerName: document.getElementById('ownerName').value.trim(),
      carModel: document.getElementById('carModel').value.trim(),
      licenseNumber: document.getElementById('licenseNumber').value.trim(),
      registrationDate: document.getElementById('registrationDate').value,
    };
  
    if (!registration.ownerName || !registration.carModel || !registration.licenseNumber || !registration.registrationDate) {
      alert('Please fill out all fields.');
      return;
    }
  
    saveRegistration(registration);
    form.reset();
  });
  
  // Edit a registration
  window.editRegistration = function (index) {
    const registrations = JSON.parse(localStorage.getItem('registrations')) || [];
    const registration = registrations[index];
  
    document.getElementById('ownerName').value = registration.ownerName;
    document.getElementById('carModel').value = registration.carModel;
    document.getElementById('licenseNumber').value = registration.licenseNumber;
    document.getElementById('registrationDate').value = registration.registrationDate;
  
    editIndex = index; // Set index for editing
  };  

Final Output:

create-car-registration-system-using-html-css-and-javascript.gif

Conclusion:

In this tutorial, we’ve successfully created a simple Car Registration System using HTML, CSS, and JavaScript. You learned how to:

  • Build the form structure with HTML
  • Style the form using CSS
  • Add form validation and handle submission with JavaScript

This is just a basic example, and you can expand it further by adding more complex features, such as saving the data to a database or sending confirmation emails. With these skills, you’re now equipped to create a functional car registration system for any project!

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🥺