How to create an editable HTML table cell using the <td> element

When pulling information from a database table and placing it into an HTML table, I encountered an issue with allowing the user to edit the data. I attempted to use jQuery to create a click event for editing, but when utilizing <textarea> or <input>, it caused the cell to enlarge and disrupt the appearance of the entire table. Can the table cell itself be converted into an input field? The challenge is finding the best option for text editing without compromising the table layout. My ultimate goal is to update the value back to the database once it has been edited by the user.

I have attached two screenshots for reference - the first displaying the original table design, and the second illustrating how it appears distorted when a <textarea> is added.
Screenshot of Table
Screenshot of Table with Textarea

<?php
    include("connection.php");
    $query= "SELECT * FROM schedule";
    $result = mysqli_query($link, $query);
    $scheduletext="<table>";
    if($result = mysqli_query($link, $query)) {
        $b=1;
        while ($row=mysqli_fetch_array($result)) {
            $scheduletext.="<tr>";
            $a=1;
            while($a< mysqli_num_fields($result)) {
                if(($a == 1)and ($b == 1)){
                    $scheduletext.="<th></th>";
                } else {
                    if (($a == 1) or ($b == 1)) {
                        $scheduletext.="<th>".$row[$a]."</th>";
                    } else {
                        $scheduletext.="<td>".$row[$a]."</td>";   
                    }
                }
                $a++;
            }
            $scheduletext.="</tr>";
            $b++;
        }
    }
    $scheduletext=$scheduletext."</table>";
?>
<html>
  <head>
    <title>TastySnack - Production Schedule</title>
    <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">   
    <link rel="stylesheet" type="text/css" href="tasty.css">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  </head>
  <body>
    <div id="top">
        <div id="top-left">
            TastySnack Production
        </div>
        <div id="top-right">
            <img id="logo" src="images/TastysnackLogo.jpg">
        </div>
    </div>
    <div id="split"></div>
    <div id="schedule">
        <?php 
            print_r($scheduletext);
        ?> 
        <div id="new"></div>
    </div>
    <script type="text/javascript">
        $("td").click(function(){
            $(this).html("<textarea>");
        });
    </script>
  </body>
</html>

Answer №1

To make the content editable, simply add "contenteditable" to the td element where you want it

 <td contenteditable>hello world</td>

Check out this demo: https://jsfiddle.net/3eav7mLv/

Answer №2

If you want to make editing and deleting tables easier, consider using jquery table edit. You can find more information about it here.

  1. First, download and include the js table edit file.
  2. Next, use code from the example below:

    $('#example3').Tabledit({ 
    url: 'example.php',
    editButton: false,
    deleteButton: false,
    hideIdentifier: true,
    columns: {
    identifier: [0, 'id'],
    editable: [[2, 'firstname'], [3, 'lastname']]
    }});
    

    This is where

example.php

You can customize this route for your controller with specific logic.

Answer №3

To add a text input field or a textarea within a table cell, simply insert the <textarea> or <input type="text"> element inside the <td> tag

<td><textarea rows="4" cols="50">Your content here</textarea></td>

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

JavaScript powered Scrolling Image Gallery

I want to create a flash gallery similar to this website using Javascript. Does anyone know of any resources or examples I can reference for this project? ...

Custom fields in WooCommerce can be listed with commas if a certain condition is met

Running a book store on WooCommerce, I have customized fields for book products: Author Publisher Year My goal is to format the products page like this: /// Image /// (/br) PROD.NAME(/br) Author(/br) Publisher, Year(/br) Price and Add to Cart button be ...

Is it possible to adjust the height of the navbar in Bootstrap?

Currently, I am in the process of replicating the mac OS navbar and am seeking guidance on resizing the navbar height and adjusting text size to around 12px. This is my first time working with bootstrap, so any assistance would be greatly appreciated. Addi ...

Guide to displaying a server response within a React application

Is there a way for me to synchronize the data retrieved from the server with the template in my component? I am trying to fetch data from the server, perform some parsing, and then display it in a table within the component. However, the issue is that the ...

Is it not possible to apply the .includes method on a string within a v-if directive while utilizing a computed property?

Problem I am facing an issue while trying to determine if a string contains a substring within the Vues v-if directive. The error message I receive is: TypeError: $options.language.includes is not a function The technologies I am using are Vue, Vuex, and ...

A Guide to Utilizing Parameters in Javascript Strings

I'm in search of a solution but struggling to find a comprehensive explanation. I am working on a code where I need the flexibility to easily update strings or other parameters. What I aim for is passing values to a string when calling it through a ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Changing URL Links to Plain Text with Regular Expressions

When sending an email from my application, I am primarily using HTML format and applying a regex to remove the HTML tags for a plain-text alternative view. (using @"<(.|\n)*?>"). My goal is to substitute the <a> hyperlink tag with a plain- ...

Designing a dynamic class object for a material table

I am in need of assistance with creating an HTML table using data retrieved from an API. The structure of the data is as follows: { strTableName: "TestTable", strComment:"Approved", lstTableHeaders:[ {strFieldName : "Sl No.", strType:" ...

Is it possible for Bootstrap to hide a grid column on extra small screens by setting its column width to zero?

Is there a specific Bootstrap class that allows me to hide a grid column for certain screen sizes without using media queries and the "display:none" style? ...

What is the best way to display the current time (generated through JavaScript) within a designated div element?

During my JavaScript studies, I stumbled upon the following code snippet: function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.body.innerHTML = hours+":"+mins+":"+sec ...

Is it possible to personalize a select button for both iOS and Android mobile platforms?

I've implemented a dropdown on my website for the desktop version and it works fine. However, I want to replace this dropdown with a select button on iPad and iPhone, as I prefer how it looks on those devices. Is it possible to style the select butto ...

What is the best way to calculate the duration of a .wav file stored locally using JavaScript?

Can you help me figure out how to determine the duration (in milliseconds) of a .wav file using JavaScript for a GreaseMonkey Script? The main challenges I'm encountering are: 1) Accessing local files 2) Retrieving the length of the wav file ...

Using Node.js with the express framework for requiring and posting data

main.js: var mainApp = express(); require('./new_file.js')(mainApp); new_file.js: mainApp.post('/example', function(req, res) { console.log(true); }); Error message: mainApp is not defined. Looking for a solution to access exp ...

Performing mathematical computations through a mixin without relying on inline javascript code

Looking to enhance my web app with a mixin that shows a list of entries, each with a time stamp indicating how long ago it was posted. mixin listTitles(titles) each title in titles article.leaf article a.headline(href=title.URL)= title.t ...

Error encountered while trying to add foreign keys in MySQL database

When attempting to add a foreign key to my Table using the following query: $query = "ALTER TABLE reserved ADD CONSTRAINT fk_test FOREIGN KEY (personel_num) REFERENCES members (personel_num) ON DELETE CASCADE ON UPDATE;"; if ($conn->query($query) === T ...

The Javafx WebEngine's executescript() function is unable to send a multiline string

Issue: I'm struggling to make the JavaFX WebEngine trigger a JavaScript function when using a Java String object with multiple lines. If I input the following example in HTML: "asd" ENTER "qwe" into the textArea, and then click the send button, the f ...

Transform JSON arrays into JSON structure

I'm currently facing an issue with converting JSON arrays to JSON format data. The output I am currently getting looks like this: https://i.stack.imgur.com/SW2NW.png However, I would like my output to be in the following format: https://i.stack.img ...

Maximum opacity in Three.js fog

My Current Endeavor: I am in the process of developing a lightweight GIS application with topography. One feature I want to implement is atmosphere haze. The Code I'm Working With: (Please bear with me as I have multiple scenes) fogColor = new T ...

The parent font size is influenced by the font size of the child element

I am encountering an issue with my code that seems to be quite simple. Here is the code snippet: <p> <h3>Title is here</h3> This is the paragraph </p> Here is the CSS: h2 {font-size:2.3em;} h3 {font-size:1em;} p {font-size:0. ...