Can CSS be used to conceal an empty <table> row?

I am currently learning the fundamentals of JavaScript and HTML5 with a project in mind. My goal is to develop a cookbook application where users can input their recipes. These recipes will be stored in an array and displayed in a table using a for loop. Users will also have the ability to edit the table entries. An important feature I am trying to implement is automatic deletion of empty rows in the table. I initially attempted to use CSS styling with display: none, but it did not yield the desired result. Below is my CSS code for the table:

form.addEventListener("submit", function (event) {
  let titleRow = table.insertRow();
  let stepsRow = table.insertRow();
  let titleCell = titleRow.insertCell();
  let stepsCell = stepsRow.insertCell();
  titleCell.innerHTML = inputTitle.value;
  stepsCell.innerHTML = inputSteps.value;
  titleCell.contentEditable = true;
  stepsCell.contentEditable = true;
  inputTitle.value = inputTitle.defaultValue;
  inputSteps.value = inputSteps.defaultValue;
}, false);
td: empty {
    display: none;
}
tr: empty {
    display: none;
}
<form id="form">
           <label>Insert Recipe: </label>
       <textarea id = "inputTitle" rows="1" cols="50" placeholder="Recipe Title"></textarea>
           <textarea id = "inputSteps" rows = "5" cols = "50" placeholder="Recipe Steps"></textarea>
       <button type="submit">Add Recipe</button>
</form>
<table id = "table"></table>

The table element represents an HTML5 table, while inputTitle and inputSteps are references to different textareas.

I acknowledge that there may be errors in my JavaScript implementation.

Your insights and assistance are greatly appreciated!

Answer №1

In order to prevent submitting data to unnecessary resources, it is recommended not to utilize a form or a submit button.

An easy solution would be to validate the inputs before constructing the table. If the input is empty, simply refrain from creating those rows.

Additionally, avoid using .innerHTML if the string being manipulated does not include any HTML content. Instead, opt for .textContent as it has better performance and security considerations.

let inputTitle = document.getElementById("inputTitle");
let inputSteps = document.getElementById("inputSteps");

document.querySelector("button").addEventListener("click", function (event) {
  // First, just check to see if there was valid input
  if(!inputTitle.value || !inputSteps.value){
    alert("You must fill in a title and a recipe");
    return;  // Exit function
  }
  let titleRow = table.insertRow();
  let stepsRow = table.insertRow();
  let titleCell = titleRow.insertCell();
  let stepsCell = stepsRow.insertCell();
  titleCell.textContent = inputTitle.value;
  stepsCell.textContent = inputSteps.value;
  titleCell.contentEditable = true;
  stepsCell.contentEditable = true;
});
<label>Insert Recipe: </label>
<textarea id = "inputTitle" rows="1" cols="50" placeholder="Recipe Title"></textarea>
<textarea id = "inputSteps" rows = "5" cols = "50" placeholder="Recipe Steps"></textarea>
<button type="button">Add Recipe</button>
<table id = "table"></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 transform a JSON object into a formatted string using Vue?

I have a dynamically set JSON object that needs to be manipulated. The method onDragStop is used to set the columns: data() { return { columns: [], } }, methods: { onDragStop: function (index) { this.$set(this.columns, index, { xAxis: ...

Having trouble displaying an image in the background using CSS? Look no further than Laravel

After running the command php artisan storage:link, I am facing an issue where the image does not load. Upon inspection, it displays a message saying "Could not load the image". https://i.sstatic.net/KKFy9.png What adds to my confusion is that ...

Angular directive undergoing karma testing throws an error: $sce:insecurl

Currently, I am in the process of creating a test for a directive known as calendar week. During this development, I encountered an angular error that led me to the following link: https://docs.angularjs.org/error/$sce/insecurl?p0=http:%2F%2Fhere.com%2Fvie ...

creating a clickable link in a datagrid using asp.net

In my DataGrid, I have organized information into 3 columns: a Problem id, Solution, and Hyperlink. I am looking to have the hyperlink open in a new window with a parameter of ProblemId. Additionally, I would like the size of the new window to be small. ...

Is there a way to initiate LiveServer or npm run dev/start over my local network?

Is it possible to access my project (npm run dev/liveServer) over my home internet network so that my iPad, phone, or iMac could also view the project live as it's being developed (all connected to the same wireless network) without the need to deploy ...

The horizontal scrolling feature in tables is not functioning properly on iOS Safari

Having trouble getting a horizontal scroll to work on my table in a React app, specifically on iOS Safari. It works fine on other platforms. Here is a snippet from my JS file: <div className={styles.parent}> <div className={styles.wrapper}> ...

What is the best way to create a text shadow effect for a heading element?

Is it possible to create a centered heading like the one in this image using only CSS, without using flexbox? [EDIT] Below is an example using flexbox. However, there are some limitations with this code as it doesn't allow reusing the same class for ...

Encountering an issue: Unable to load resources - Server returned a status code of 500

Struggling with implementing ajax code in my app development. I've encountered an issue where the ajax code that works fine in the video tutorials I'm following doesn't seem to work for me. It's really frustrating! Here is a snippet of ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

Using an iframe with THREE.js and WebGlRenderer can result in the domElement's getBoundingClientRect method returning 0

I encountered an issue with my code: ... renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setSize(WIDTH, HEIGHT); ... controls = new TrackballControls(camera, renderer.domElement); Strange behavior occurs when I r ...

Is there a way to dynamically update a controller variable using AJAX in Ruby on Rails

After selecting a row in my table, I aim to update a variable in the view using JavaScript. Here is the function I currently have: $("#myTable tr").click(function(){ var rowData = $(this).children("td").map(function() { return $(this).text(); }).get(); ...

Exploring AngularJS Scope Feeds through Looping

Can someone guide me on how to iterate through this data using AngularJS? I'm comfortable with using var_dump in HTML with Laravel, but I need help debugging and looping through this data in Angular. Any suggestions? $scope.feed = result.data; https ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

Modify text using JQuery when the span is clicked

Currently, I am attempting to retrieve a value from the database: SenderDriver->total_trips. Everything seems fine, but I have a specific id that needs to be placed within onClick(), which then sets the value of the database variable: SenderDriver-> ...

Achieve perfect alignment of an HTML table by positioning it precisely 36 pixels away from the right edge of the window

I'm struggling to achieve a table that is precisely 36px away from both the left and right edges of the browser window, regardless of CSS. While I can easily set the left margin, getting the exact right margin seems impossible as the `margin-right` CS ...

"Improprove your website's user experience by implementing Material UI Autocomplete with the

Recently, I experimented with the Autocomplete feature in Material UI. The focus was on adding an option when entering a new value. You can check out the demo by clicking on this link: https://codesandbox.io/s/material-demo-forked-lgeju?file=/demo.js One t ...

What is the best way to create a design with an image on the left and text on the right side?

I am trying to create a layout that features an image on the left and text on the right in a specific structure: Item 0: value 0 Item 1: value 1 Item 2: value 2 However, the text is appearing all in one row like this: Item 0: value 0 Item 1: value 1 Ite ...

Encountering the error "ReferenceError: data not defined" while utilizing JSONP in my code

I'm encountering an issue when trying to display JSON data using JSONP. I have a complex JSON file that is being delivered from a different domain via a URL and my expertise in JSON and ajax is limited. After following a tutorial on JSONP at https://l ...