The HTML/JS output displays a table with missing horizontal borders

Why aren't my horizontal borders showing up in the output section? Take a look at the code and screenshot below: I want to include horizontal borders and prevent the date fields from moving to the row below. https://i.sstatic.net/qO1KC.png

I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.

           <td align="center"><input type="button" value="Submit" name="submit" id="submit" onClick="display()" /></button></td>
    </tr>
</table>
<table width="400px" align="center" colspan="40" table border="5">

    <tr style="background-color:#8FBC8F;">
        <td align="center"><b>Name</b></td>
        <td align="center"><b>Company</b></td>
        <td align="center"><b>Time In</b></td>
        <td align="center"><b>Time Out</b></td>
        <td align="center"><b>Description of Work</b></td>
    </tr>
    <tr>
        <td align="center"><div id="displayarea"></div></td>
        <td align="center"><div id="displayarea1"></div></td>
        <td align="center"><div id="displayarea2"></div></td>
        <td align="center"><div id="displayarea3"></div></td>
        <td align="center"><div id="displayarea4"></div></td>
    </tr>

I am trying to achieve horizontal borders while keeping the date fields intact.

function getValue() {
        var Items = "";
        var td1 = document.getElementById("displayarea").innerHTML.split("<br>");
        var td2 = document.getElementById("displayarea1").innerHTML.split("<br>");
        var td3 = document.getElementById("displayarea2").innerHTML.split("<br>");
        var td4 = document.getElementById("displayarea3").innerHTML.split("<br>");
        var td5 = document.getElementById("displayarea4").innerHTML.split("<br>");

        for (var i = 0; i < td1.length; i++) {
            if (td1[i])
                Items += td1[i] + " ,";
            if (td2[i])
                Items += td2[i] + " ,";
            if (td2[i])
                Items += td2[i] + " ,";
            if (td3[i])
                Items += td3[i] + " ,";
            if (td4[i])
                Items += td4[i] + " ";
            Items += "\n";
            
            
        }
        console.log(Items);
        return Items;
    }

    function display() {
        document.getElementById("displayarea").innerHTML += document.getElementById("fname").value + "<br />";
        document.getElementById("fname").value = "";
        document.getElementById("displayarea1").innerHTML += document.getElementById("lname").value + "<br />";
        document.getElementById("lname").value = "";
        document.getElementById("displayarea2").innerHTML += document.getElementById("sname").value + "<br />";
        document.getElementById("sname").value = "";
        document.getElementById("displayarea3").innerHTML += document.getElementById("pname").value + "<br />";
        document.getElementById("pname").value = "";
        document.getElementById("displayarea4").innerHTML += document.getElementById("jname").value + "<br />";
        document.getElementById("jname").value = "";
    }

Answer №1

Why not consider separating your data from its presentation?

You could break up your display function into two distinct parts: createRow and renderRows. Similarly, instead of using getValues, simply use getRows.

It's important to note that this approach will require some adjustments to your code structure. In addition, I took the liberty of modernizing your HTML and CSS to adhere more closely to current best practices.

function getRows(data) {
  return data.map(datum => Object.values(datum).join(',')).join('\n');
}

function createRow(data) {
  const datum = {
    fname: document.getElementById("fname").value,
    lname: document.getElementById("lname").value,
    sname: new Date(document.getElementById("sname").valueAsNumber).toLocaleString(),
    pname: new Date(document.getElementById("pname").valueAsNumber).toLocaleString(),
    jname: document.getElementById("jname").value
  };
  data.push(datum);
  document.getElementById("dataForm").reset();
  renderRows(data);
}

function renderRows(data) {
  const body = document.getElementById("renderedData");
  body.innerHTML = "";
  for (let datum of data) {
    let tr = document.createElement('tr');
    let tdFName = document.createElement('td');
    tdFName.appendChild(document.createTextNode(datum.fname));
    tr.appendChild(tdFName);
    let tdLName = document.createElement('td');
    tdLName.appendChild(document.createTextNode(datum.lname));
    tr.appendChild(tdLName);
    let tdSName = document.createElement('td');
    tdSName.appendChild(document.createTextNode(datum.sname));
    tr.appendChild(tdSName);
    let tdPName = document.createElement('td');
    tdPName.appendChild(document.createTextNode(datum.pname));
    tr.appendChild(tdPName);
    let tdJName = document.createElement('td');
    tdJName.appendChild(document.createTextNode(datum.jname));
    tr.appendChild(tdJName);
    body.appendChild(tr);
  }
}
window.addEventListener('load', () => {
  const data = [];
  document.getElementById('add').addEventListener('click', function(e) {
    createRow(data);
  });
  document.getElementById('getData').addEventListener('click', function(e) {
    console.log(getRows(data));
  });
});
form {
  width: max-content;
  margin: 0 auto 1rem;
}
.control-group {
  display: flex;
  justify-content: space-between;
}
fieldset {
  display: flex;
  flex-flow: column nowrap;
}

fieldset button {
  align-self: flex-end;
}
<form id="dataForm">
  <fieldset>
    <legend>Enter Data</legend>
    <div class="control-group">
      <label for="fname">Name:</label>
      <input id="fname" type="text">
    </div>
    <div class="control-group">
      <label for="lname">Company:</label>
      <input id="lname" type="text">
    </div>
    <div class="control-group">
      <label for="sname">Time In:</label>
      <input id="sname" type="datetime-local">
    </div>
    <div class="control-group">
      <label for="pname">Time Out:</label>
      <input id="pname" type="datetime-local">
    </div>
    <div class="control-group">
      <label for="jname">Description of Work:</label>
      <textarea id="jname"></textarea>
    </div>
    <button type="button" id="add">Add</button>
  </fieldset>
</form>
<table width="400px" align="center" colspan="40" table border="5">
  <thead>
    <tr style="background-color:#8FBC8F;" id='header'>
      <td align="center"><b>Name</b></td>
      <td align="center"><b>Company</b></td>
      <td align="center"><b>Time In</b></td>
      <td align="center"><b>Time Out</b></td>
      <td align="center"><b>Description of Work</b></td>
    </tr>
  </thead>
  <tbody id="renderedData">
  </tbody>
</table>
<button type="button" id="getData">Get Data</button>

Answer №2

If you want to give all cells borders, simply include the following snippet at the beginning of your HTML code (within the head):

<style>
  table { 
    border-collapse: collapse; 
  }
  td {
    border: 1px solid #555;
  }
</style>

You can customize the border thickness, style, and color to suit your preferences by adjusting the values in the border property of the td element.

Answer №3

If you want to dynamically add rows with each addition, one easy way is to use the https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template element. This method works well in modern browsers, although older ones like Internet Explorer might lag behind.

I've made a tweak in how the values are read, using classes instead of IDs in the cells within the rows. This adjustment allows for an easier collection of values with minimal changes to your existing code.

Personally, I prefer getting row data in a different way, as demonstrated in the alternativeGetValues function below.

function getValue() {
    var Items = "";
    var td1 = [...document.querySelectorAll(".displayarea")].map(e => e.innerHTML);
    var td2 = [...document.querySelectorAll(".displayarea1")].map(e => e.innerHTML);
    var td3 = [...document.querySelectorAll(".displayarea2")].map(e => e.innerHTML);
    var td4 = [...document.querySelectorAll(".displayarea3")].map(e => e.innerHTML);
    var td5 = [...document.querySelectorAll(".displayarea4")].map(e => e.innerHTML);

    for (var i = 0; i < td1.length; i++) {
        if (td1[i])
            Items += td1[i] + " ,";
        if (td2[i])
            Items += td2[i] + " ,";
        if (td3[i])
            Items += td3[i] + " ,";
        if (td4[i])
            Items += td4[i] + " ,";
        if (td5[i])
            Items += td5[i] + " ";
        Items += "\n";

    }
    console.log(Items);
    return Items;
}

function display() {
    const template = document.getElementById("row");
    const clone = template.content.cloneNode(true);
    const additem = (dest, src) => {
        const s = document.querySelector(src);
        clone.querySelector(dest).innerHTML = s.value;
        s.value = "";
    };
    additem(".displayarea", "#fname");
    additem(".displayarea1", "#lname");
    additem(".displayarea2", "#sname");
    additem(".displayarea3", "#pname");
    additem(".displayarea4", "#jname");
    template.insertAdjacentElement('beforebegin', clone.firstElementChild);
}

// In my opinion, this approach is more efficient
function alternateGetValue() {
    const Items = [...document.querySelectorAll('.data')]
        .map(row => [...row.querySelectorAll('td>div')]
            .map(d => d.textContent).join(',')
        ).join('\n');
    console.log(Items);
    return Items;
}
.wide {
  min-width:12em;
}
F: <input id="fname"> <br>
L: <input id="lname"> <br>
S: <input id="sname"> <br>
P: <input id="pname"> <br>
J: <input id="jname"> <br>
<input type="button" value="add" onclick="display()"/>
<input type="button" value="show" onclick="getValue()"/>
<input type="button" value="Better" onclick="alternateGetValue()"/>
<table width="400px" align="center" colspan="40" table border="5">
  <thead>
    <tr style="background-color:#8FBC8F;" id='header'>
        <td align="center"><b>Name</b></td>
        <td align="center"><b>Company</b></td>
        <td align="center" class="wide"><b>Time In</b></td>
        <td align="center" class="wide"><b>Time Out</b></td>
        <td align="center"><b>Description of Work</b></td>
    </tr>
  </thead>
  <tbody>
    <template id="row">
        <tr style="background-color:#8F8FBC;" class="data">
            <td align="center"><div class="displayarea"></div></td>
            <td align="center"><div class="displayarea1"></div></td>
            <td align="center"><div class="displayarea2"></div></td>
            <td align="center"><div class="displayarea3"></div></td>
            <td align="center"><div class="displayarea4"></div></td>
        </tr>
    </template>
  </tbody>
</table>

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

How to select a child element within a sibling div of a parent div using jQuery

HTML <div class="container-fluid"> <div class="input-page">...</div> <!-- field 1 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Explore Python and Selenium for implementing pagination with JavaScript functionality

Having recently started using Selenium with Python 2.7, I am looking to click on certain JavaScript elements used for pagination on a website. To provide context, here is the link to the page: . Any guidance or example code would be greatly appreciated. ...

How does the max() function in JavaScript handle arrays when there are multiple numbers of the same maximum value?

Assuming we have the following scenario: array=[5,5,5,5,3,2]; return Math.max.Apply(Math,array); How can I modify the code to output the numbers in sequential order from first to last? ...

Is there a way to implement jquery (or other external libraries) within Typescript?

Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverag ...

tips on resizing a dragged item to fit into a dropped container using jQuery

Is there a way to adjust the size of a dragged element to match its parent's dimensions after successfully dragging it (ensuring that both elements have the same width and height)? Does anyone know how to accomplish this alignment between the two ele ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

display select items from a webpage

Despite researching many topics, I am still unable to get this to work. My goal is to hide certain elements on my webpage when the user tries to print it. I am currently using Bootstrap 5, which includes the following CSS: @media print{.d-print-none{disp ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...

Firefox presents a compact box positioned between the images

When attempting to use flags as a way to switch between languages, I encountered an issue in Firefox where a small box appears between the images on the Hebrew site. In Chrome, everything works fine. I implemented the following code: <div class="flags ...

An error was encountered because it was unable to read properties of undefined, specifically in trying to access 'navigate'

Just diving into the world of react native and react navigation, I encountered this puzzling error. Uncaught TypeError: Cannot read properties of undefined (reading 'navigate') I'm scratching my head because I am using the exact same code ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Newly imported App component not appearing in App JS after import

Whenever I add a new component called cart.js in the app.js file, the app stops rendering anything on the browser without throwing any errors. Surprisingly, the modal.js code is also shared here as it acts as a wrapper for the cart component. Interestingly ...

Adjust the map zoom and boundaries for all markers on Google API v3

I have been struggling with implementing latlngbounds to dynamically fit all the pins in the map canvas. If anyone has experience with a similar issue and can provide guidance on where my code might be going wrong, I would greatly appreciate it. var geo ...

Creating a Website Optimized for Mobile Devices

As a beginner web developer, I am in the process of creating a mobile-friendly website system. Currently, I am utilizing Bootstrap for responsiveness, PHP5, MySQL, and occasionally Ajax/JQuery. Recently, I came across JQuery Mobile. While I have been usin ...

Unable to Apply Margin to Element within ASP.Net View Code Section

I've exhausted all my ideas and even searched Google without finding a solution. <div class="col-md-12"> <div class="card-header text-white" style="background-color:cornflowerblue"> <div class=& ...

Exploring the getInitialProps function in NextJS

I'm currently exploring NextJS and came across a sample page implementation: class IndexPage extends Component { static async getInitialProps(context) { return {}; } render() { return <div>hello world</div>; } } export def ...

What is the best way to insert a hyperlink into the header of a column in a React table that is built using Material

// Here is the header const dataCells = [ {id:"Customer_ID",label:"CustomerId"}, {id:"Type", label: "Type"}, {id:"First_Name", label: "First Name"}, {id:"Last_Name", labe ...

Utilizing VueJs @error handler for managing broken image links

I am encountering a strange issue with the VueJS @error handler. My goal is to hide images with broken links and display a placeholder instead. However, when I have two images with broken links, only the first image displays the placeholder while the other ...