Seeking to implement a feature where Javascript adds input from a form into an HTML table in real-time?

Attempting to achieve this goal involves creating an array that holds an object with instance variables related to form input. After that, the next step is to add whatever was submitted from the form to the table. However, upon calling the function to accomplish this task, nothing seems to happen. I am struggling to identify where exactly the mistake lies in this process. It's worth noting that all of this is being implemented using bootstrap 4.

var locationList = [];

function locations_addAndSave() {
var locationForm = document.forms['locations'];
var city = locationForm.elements['city'].value;
var opening = locationForm.elements['opening'].value;
var closing = locationForm.elements['closing'].value;

var locationData = new Object();
locationData.city = city;
locationData.opening = opening;
locationData.closing = closing;

locationList.push(locationData);

var locationHtml = addLocations(locationList);
var table = document.getElementById("locationTable");
table.innerHTML = locationHtml;
}

function addLocations(locationList) {

var newTable = "";
for (var i = 0; i < locationList.length; i++) {
newTable += "<tr>";
newTable += "<td>";
newTable += locationList[i].city;
newTable += "</td>";
newTable += "<td>";
newTable += locationList[i].opening;
newTable += "</td>";
newTable += "<td>";
newTable += locationList[i].closing;
newTable += "</td>";
}
}
<table class="table table-bordered" id="locationTable">
<thead>
<tr>
<th>City</th>
<th> Opens (AM) </th>
<th>Closes(PM)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Calgary</td>
<td>9</td>
<td>9</td>
</tr>
<tr>
<td>Edmonton</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>ancouver</td>
<td>11</td>
<td>10</td>
</tr>
</tbody>
</table>


<form action="ignore this" name="locations">
<div class="form-group">
<label for="city">City</label>
<input type="text" name="city" placeholder="Enter city">
</div>
<div class="form-group">
<label for="closing">Opening</label>
<input type="text" name="opening" placeholder="Enter Opening time 9-11 AM">
</div>
<div class="form-group">
<label for="">Closing</label>
<input type="text" name="closing" placeholder="Enter Closing time 8-10 PM">
</div>
<button type="button" class="btn btn-default" onclick="locations_addAndSave()">Add Location </button>
</form>

var locationList = [];

function locations_addAndSave() {
var locationForm = document.forms['locations'];
var city = locationForm.elements['city'].value;
var opening = locationForm.elements['opening'].value;
var closing = locationForm.elements['closing'].value;

var locationData = new Object();
locationData.city = city;
locationData.opening = opening;
locationData.closing = closing;

locationList.push(locationData);

var locationHtml = addLocations(locationList);
var table = document.getElementById("locationTable");
table.appendChild(locationHtml);
}

function addLocations(locationList) {

var newTable = document.createElement('tr');
for (var i = 0; i < locationList.length; i++) {
var newCell1 = document.createElement('td');
newCell1.innerText = 'locationlist[i].city';
newTable.appendChild(newCell1);
var newCell2 = document.createElement('td');
newCell2.innerText = 'locationlist[i].opening'
newTable.appendChild(newCell2);
var newCell3 = document.createElement('td');
newCell.innerText = 'locationlist[i].closing';
newTable.appendChild(newCell3);
}

return newTable;
}

Answer №1

Creating new rows as strings may not be effective without a library like jQuery to append them to the DOM seamlessly.

An alternative approach is to utilize the native DOM API:

const freshRow = document.createElement('tr');

This allows for full manipulation of the row using the DOM API.

freshRow.classList.add('some-class');
freshRow.style = '...';

const brandNewCell = document.createElement('td');
brandNewCell.innerText = 'Something!'

You can then place that cell within your new row

freshRow.appendChild(brandNewCell);

resulting in a genuine element containing your row.

Next, select your table

const selectedTable = document.querySelector('#your_table');
selectedTable.appendChild(freshRow);

Your table should now display a newly added row at the end.

Sorting rows adds complexity, but remains achievable.

Answer №2

Don't forget to include the operator '+' in your JavaScript code

var locationHtml = addLocations(locationList);
var table = document.getElementById("locationTable");
table.innerHTML += locationHtml; //remember this

You can also utilize ES6 String Interpolation instead of the following lines:

newTable += "<tr>";
newTable += "<td>";
newTable += locationList[i].city;
newTable += "</td>";
newTable += "<td>";
newTable += locationList[i].opening;
newTable += "</td>";
newTable += "<td>";
newTable += locationList[i].closing;
newTable += "</td>";

Simply write:

newTable += `<tr><td>${locationList[i].city}</td><td>${locationList[i].opening}</td><td>${locationList[i].closing}</td></tr>`;

Answer №3

If you're looking to implement your functionality using jQuery, here's one approach you can follow:

var locationList = [];

$( "#locations" ).submit(function( e ) {
  e.preventDefault();
  
  var city = $("input[name='city']").val();
  var opening = $("input[name='opening']").val();
  var closing = $("input[name='closing']").val();
  
  var html = '<tr><td>'+city+'</td><td>'+opening+'</td><td>'+closing+'</td></tr>';
  
  $('#locationTable tbody').append(html);
  $('#locations')[0].reset();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="locationTable">
  <thead>
    <tr>
      <th>City</th>
      <th> Opens (AM) </th>
      <th>Closes(PM)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Calgary</td>
      <td>9</td>
      <td>9</td>
    </tr>
    <tr>
      <td>Edmonton</td>
      <td>8</td>
      <td>8</td>
    </tr>
    <tr>
      <td>ancouver</td>
      <td>11</td>
      <td>10</td>
    </tr>
  </tbody>
</table>


<form name="locations" id="locations">
  <div class="form-group">
    <label for="city">City</label>
    <input type="text" name="city" placeholder="Enter city">
  </div>
  <div class="form-group">
    <label for="closing">Opening</label>
    <input type="text" name="opening" placeholder="Enter Opening time 9-11 AM">
  </div>
  <div class="form-group">
    <label for="">Closing</label>
    <input type="text" name="closing" placeholder="Enter Closing time 8-10 PM">
  </div>
  <input type="submit" class="btn btn-default" value="Add Location">
</form>

Answer №4

Kindly review the updated code below

var locations = [];

function addLocation() {
  var form = document.forms['locations'];
  var city = form.elements['city'].value;
  var opening = form.elements['opening'].value;
  var closing = form.elements['closing'].value;

  var location = {
    city: city,
    opening: opening,
    closing: closing
  };

  locations.push(location);

  var tableHtml = buildTable(locations);
  var table = document.getElementById("locationTable");
  table.innerHTML += tableHtml;
}

function buildTable(locations) {
  var newTable = "";

  for (var i = 0; i < locations.length; i++) {
    newTable += "<tr>";
    newTable += "<td>";
    newTable += locations[i].city;
    newTable += "</td>";
    newTable += "<td>";
    newTable += locations[i].opening;
    newTable += "</td>";
    newTable += "<td>";
    newTable += locations[i].closing;
    newTable += "</td>";
  }
  return newTable;
}
<table class="table table-bordered" id="locationTable">
  <thead>
    <tr>
      <th>City</th>
      <th> Opens (AM) </th>
      <th>Closes(PM)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Calgary</td>
      <td>9</td>
      <td>9</td>
    </tr>
    <tr>
      <td>Edmonton</td>
      <td>8</td>
      <td>8</td>
    </tr>
    <tr>
      <td>Vancouver</td>
      <td>11</td>
      <td>10</td>
    </tr>
  </tbody>
</table>


<form action="ignore this" name="locations">
  <div class="form-group">
    <label for="city">City</label>
    <input type="text" name="city" placeholder="Enter city">
  </div>
  <div class="form-group">
    <label for="closing">Opening</label>
    <input type="text" name="opening" placeholder="Enter Opening time 9-11 AM">
  </div>
  <div class="form-group">
    <label for="">Closing</label>
    <input type="text" name="closing" placeholder="Enter Closing time 8-10 PM">
  </div>
  <button type="button" class="btn btn-default" onclick="addLocation()">Add Location </button>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing Wordpress by Efficiently Enqueueing Javascript

As a beginner with a WordPress website, I am aware that in order to execute scripts on a WordPress page, they need to be enqueued in the functions.php file. However, I'm unsure about the correct process for this. The specific JavaScript file I want t ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Vuex data fails to update upon browser reload in Nuxt SSR

After explaining the bug, I discovered something interesting; Component codes async fetch(){ await this.$store.dispatch('bots/getBots') }, computed: { ...mapState('bots', ['bots']) }, Store codes export const state = () ...

An efficient JavaScript regular expression pattern that allows for both alphanumeric and special characters

Looking for a javascript regex that allows alphanumeric and special characters exclusively. The following regex was attempted but did not work: /^(?!.*(<|>)).*[a-zA-Z0-9 \\\\@!#$%^&*()_+-={}:;'\",.?|\[\&bs ...

"Utilizing GroupBy and Sum functions for data aggregation in Prisma

I am currently working with a Prisma schema designed for a MongoDB database model orders { id String @id @default(auto()) @map("_id") @db.ObjectId totalAmount Int createdAt DateTime @db.Date } My ...

Passing a function into the compile method in AngularJS: A comprehensive guide

I have created a directive called pagedownAdmin with some functionality to enhance the page editor: app.directive('pagedownAdmin', ['$compile', '$timeout', function ($compile, $timeout) { // Directive logic here... }]); ...

I successfully developed a unique custom accordion feature in React.js, where the toggle functionality is fully functional. However, I am currently facing an

import React, { useState, useEffect } from "react"; import axios from "axios"; const Faq = () => { const [faq, setFaq] = useState([]); const [activeIndex, setActiveIndex] = useState(null); const fetchFaqs = async () => { ...

ASP.NET: How to Leverage UpdatePanel with OnLoad Event

I am attempting to run some javascript code during the OnLoad event of my UpdatePanel like this: <asp:UpdatePanel ID="updDropDowns" runat="server" OnLoad="javascript:ResetButtons();"> However, I am receiving an error saying "'javascript' ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

Instructions on how to extract information from a JSON response in SharePoint in order to display a list of

This is my first time working with JSON, so please be kind and patient with me :) I am currently working on a website, which can be found at http://msdn.microsoft.com/en-us/library/jj164022(v=office.15).aspx Here is a sample of the JavaScript code I am u ...

retrieving session variables from the server side in javascript

I have set a session variable in the backend (code-behind ascx.cs page) and now I need to access that same value in a checkbox checked event using JavaScript. Below is my JavaScript function code: $(document).ready(function () { $('#<%= gvPR ...

Learn the steps for generating an array of objects in AngularJS or JavaScript

I have an array named $scope.data2 and I am looking to create another array of arrays based on the data provided below: $scope.data2 = [ {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 12:30 PM" ...

What is the best way to center the image on a page?

How can I center an image on the screen with a caption? <div id="team-area"> <div class="container"> <div class="row"> <div class="col-12"> <h3 class="main-title">Our Team</h3> < ...

Building a sub-navigation menu within the main navigation menu

Can anyone help me create a submenu in my navigation menu? My CSS knowledge is limited and I'm encountering some issues. When I add a submenu to the nav menu, it displays as ul li directly. #cssmenu { background: #88BC18; width: auto; z-index ...

Display issue with flex slider thumbnail view

I am experiencing an issue with my flex slider. Everything works fine when I have 4 images, but as soon as there are more than 5 images, the thumbs view is displayed incorrectly. Does anyone know a solution to fix this problem? Here is a Screenshot for r ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

Retrieve an array from a JavaScript file, transfer it to PHP, and then convert it into JSON format

I have a JavaScript file that contains data in the form of an array. http://localhost/js/data.js The information looks something like this: var subjectCodeArray=["CS/ Computer Science","AF/ Art Faculty",...]; Now, I need to access the data from the "sub ...

CSS only accordion divs that are all opened by default with no need for jquery

My current setup involves: jsfiddle.net/wromLbq5 I would like to enable the functionality of having multiple accordion sections open simultaneously upon page load. This means that when one section is opened, the others should not close. Is there a way to ...

Troubleshooting a labeling problem in a donut chart with Chart.js

$(document).ready(function(){ function call() { $.ajax({ url: "chartjs/tempdata.php", method:"GET", cache: false, success: function(data) { console.log(data); var difference=[]; var percentage=[]; var finaldata=[]; for(var i in data) { //time.push( ...

AJAX request function is only successful on the first attempt

Currently, I am implementing AJAX functionality to verify whether a user-input ID exists in the database. If the ID is found, a check mark is displayed; if not, a cross mark is displayed. The issue arises when I input an ID for the first time, which is pr ...