Vehicle ID List

by flynn_inc

HTML

<h2>ECM Legacy Mileage</h2>

<!-- Vehicle selection -->
<label for="vehicleSelect">Vehicle:</label>
<select id="vehicleSelect">
  <option value="">-- Select Vehicle --</option>
  <option value="V001">V001</option>
  <option value="V002">V002</option>
  <option value="V003">V003</option>
</select>

<span>&nbsp;&nbsp;</span>

<!-- Number input -->
<label for="vehicleNumber">Miles:</label>
<input type="number" id="vehicleMiles" min="0" step="1">

<!-- Add button -->
<button id="addBtn">Add</button>

<!-- Table to display list -->
<table id="vehicleTable">
  <thead>
    <tr>
      <th>Vehicle</th>
      <th>Miles</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

CSS

body { font-family: Arial, sans-serif; margin: 20px; }
  table { border-collapse: collapse; margin-top: 15px; width: 300px; }
  th, td { border: 1px solid #ccc; padding: 6px; text-align: center; }
  button { cursor: pointer; }

JavaScript

(() => {
  const vehicleSelect = document.getElementById('vehicleSelect');
  const vehicleMiles = document.getElementById('vehicleMiles');
  const addBtn = document.getElementById('addBtn');
  const tableBody = document.querySelector('#vehicleTable tbody');

  // Store data as an array of objects
  let vehicleList = [];

  // Render the table
  function renderTable() {
    tableBody.innerHTML = '';
    vehicleList.forEach((item, index) => {
      const row = document.createElement('tr');

      row.innerHTML = `
        <td>${item.id}</td>
        <td>${item.miles}</td>
        <td><button data-index="${index}" class="deleteBtn">Delete</button></td>
      `;

      tableBody.appendChild(row);
    });
  }

  // Add new entry
  addBtn.addEventListener('click', () => {
    const id = vehicleSelect.value;
    const num = parseInt(vehicleMiles.value, 10);

    // Validation
    if (!id) {
      alert('Please select a vehicle ID.');
      return;
    }
    if (isNaN(num)) {
      alert('Please enter a valid number.');
      return;
    }
    if (vehicleList.some(v => v.id === id)) {
      alert('This vehicle ID is already in the list.');
      return;
    }

    // Add to list
    vehicleList.push({ id, miles: num });
    renderTable();

    // Reset inputs
    vehicleSelect.value = '';
    vehicleMiles.value = '';
  });

  // Delete entry (event delegation)
  tableBody.addEventListener('click', (e) => {
    if (e.target.classList.contains('deleteBtn')) {
      const index = parseInt(e.target.dataset.index, 10);
      vehicleList.splice(index, 1);
      renderTable();
    }
  });
})();