Tips for dynamically inserting a new column into a table at any position other than the beginning or end

I have created a dynamic table where rows and columns can be added dynamically. However, I am facing an issue where I am unable to add a new column between the first and last column of the table. Currently, new columns are only being added at the end.

$('#irow').click(function(){
    if($('#row').val()){
        $('#mtable tbody').append('<tr><td>Some Item</td></tr>');
        $('#mtable tbody tr:last td:first').html($('#row').val());
    }else{alert('Enter Text');}
});
$('#icol').click(function(){
    if($('#col').val()){
        $('#mtable tr').append($("<td>"));
        $('#mtable thead tr>td:last').html($('#col').val());
        $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))});
    }else{alert('Enter Text');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<table border="1" id="mtable" class="table table-striped table-hover individual">
    <thead><tr><td>Employee \department</td><td>Mandatory</td></tr></thead>
    <tbody></tbody>
</table><br/><br/>
<input id="row" placeholder="Enter Employee Name"/><button id="irow">Add Board</button><br/><br/>
<input id="col" placeholder="Enter department Name"/><button id="icol">Add Subject</button>

I need assistance in adding new columns between the "Employee" and "Mandatory" columns.

Kindly provide your support.

Answer №1

When adding new elements, it is important to consider whether to append or insert them. In this case, it is recommended to insert the new element. Here's an example:

$('#irow').click(function(){
    if($('#row').val()){
        $('#mtable tbody').append('<tr><td>Some Item</td></tr>');
        $('#mtable tbody tr:last td:first').html($('#row').val());
    }else{alert('Enter Text');}
});
$('#icol').click(function(){
    if($('#col').val()){
        var newCol = jQuery('<td/>', {
            text: $('#col').val()
        }).insertAfter('#mtable thead tr td:first');

        $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))});
    }else{alert('Enter Text');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="mtable" class="table table-striped table-hover individual">
    <thead><tr><td>Employee \department</td><td>Mandatory</td></tr></thead>
    <tbody></tbody>
</table><br/><br/>
<input id="row" placeholder="Enter Employee Name"/><button id="irow">Add Board</button><br/><br/>
<input id="col" placeholder="Enter department Name"/><button id="icol">Add Subject</button>

Take note of the changes made. A new td element called newCol is inserted after the first column with your specified value:

if($('#col').val()){
    var newCol = jQuery('<td/>', {
        text: $('#col').val()
    }).insertAfter('#mtable thead tr td:first');

If you wish to reverse the order, you can use:

.insertBefore('#mtable thead tr td:last');

This will add new columns before the last column. It is important to clarify the purpose of the following code:

$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))}

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

React error: Unable to iterate through items because property 'forEach' is undefined

I am trying to implement private routing validation using the following code: import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import routes from '../../routing/routes'; export default function ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

creating a function within an object that allows for chaining

My goal is to create a chainable object, but I am struggling to implement this in a function. This is the functionality I desire: $donate.ga('testing').go(value); The code for my object currently appears as follows: var $donate = { ga: fu ...

Incorporate a CSS transition duration for switching classes with JavaScript

I need assistance with adding a transition time to my JavaScript toggle class function. I had previously coded it but have now forgotten how to do so. Any guidance would be highly appreciated. <!DOCTYPE html> <html> <head> <style typ ...

How can I retrieve the top-level key based on a value within a JSON object nested in JavaScript?

If I have the value Africola for key name in the following nested JSON structure, how can I retrieve its corresponding upper-level key 'barID1' using JavaScript? { "barID1": { "address": "4 East Terrace, Sydney NSW 2000", "appStoreURL" ...

Add characterizations to object utilizing cropper plugin

After obtaining image attributes from the cropper plugin, I am looking to include two additional values: var data = $img.cropper('getData'); //Object {x: 90, y: 60, width: 720, height: 480, rotate: 0…} image_identifier = $('.image_identi ...

Managing interactions with dynamically created buttons

Our Story Greetings! I am skilled in C# and VB.net, but I am diving into the world of Javascript and React. Currently, I am building a ticket purchase app to enhance my skills. While I was able to quickly create this app using Angular, React has posed mor ...

What are the solutions for resolving the error "npm run build failed to compile React JS?"

Having trouble creating an optimized production build... Compilation failed. Module not found: Error: Unable to locate './App' in '/Users/qadeer/Desktop/Khazan/guardman/src' Did you mean 'App.js'? BREAKING CHANGE: The request ...

Tips on implementing GRID layout with Material-UI in ReactJS

I'm attempting to implement the @mui/material/Grid layout for a specific scenario, Within my Report component, I aim to display the Bar and Line charts together in one section and the Doughnut and PolarArea charts in another section, I experiment ...

jQuery issue: Inability of "Read More" span to reappear after clicking "Read Less"

Currently in the process of creating a portfolio website that showcases project descriptions with an excerpt, revealing full details upon clicking "Read More." My experience with jQuery is limited, but I managed to implement functionality where clicking "R ...

CSS: Adjusting the vertical position of text without affecting the background

I am currently working on some CSS buttons that expand in size when hovered over. I have successfully increased the text size as well, but now I am facing an issue with aligning the text a few pixels lower without affecting the background image layout. Ca ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Modify the name of the document

I have a piece of code that retrieves a file from the clipboard and I need to change its name if it is named image.png. Below is the code snippet where I attempt to achieve this: @HostListener('paste', ['$event']) onPaste(e: ClipboardE ...

Perpetual spinning of image grid

Are there any jQuery libraries available for continuous image rotation within an array? I have a collection of 30 partner logos that I would like to rotate continuously using either a jQuery library or plain CSS code. These images and information will be l ...

Looking to clean up unnecessary <b></b> tags from my Wordpress website - how can I do this?

One of my sites is located at . When inspecting the source code through the browser, I noticed the presence of empty tags. Does anyone know why these empty tags are being generated and how they can be removed? I have thoroughly searched through all files ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Harness the power of Vue.js by implementing plugin methods in your code

For my first attempt at building a SPA with Vue, I decided to re-use a few functions but encountered some issues. The error message "this.ExperienceToLevel is not a function" kept popping up and it left me puzzled. Furthermore, I'm contemplating if c ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" cla ...