What is the reason behind the jQuery .after() method inserting a row that is cramming itself into one cell?

I'm attempting to dynamically add cells to the right side of a table using jQuery when a row is clicked. I have successfully implemented inserting a new row on click, which also toggles its visibility with CSS.

However, I am encountering an issue where the .after() method seems to be placing all the HTML content inside the first cell instead of adding it as a new row in the table. I suspect this might be related to how my CSS is set up for toggling the row display, but I haven't been able to pinpoint the exact cause. Changing the CSS display property has not resolved the problem.

Any assistance or guidance on this matter would be greatly appreciated!

CSS:

.metadata {
    display: none;
}

.metadata.active {
    display: block;
}

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
    margin-right:20px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

td, th {
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    text-align: left;
    padding: 8px;
    font-weight: normal;
}

th {
    text-decoration: none;
    font-size: 15px;
}

tr:nth-child(even) {
    background-color: #F5F5F5;
}

.content:hover {
    background-color: #99d1db;
    cursor: pointer;
}

HTML:

<div class="table" style="text-align:center;">

    <table>
    <tbody>
    <tr>
        <th></th>
        <th >blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
    </tr>
    <tr class="content">
        <td><input type="checkbox" name="tablebox" value="checker"></td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
    </tr>
    </tbody>
    </table>

JS:

$(document).ready(function(){
    $('body').on('click','table tr', function(){
        var row = $(this).closest('tr');
        if (row.next().hasClass("metadata")) {
            row.next().toggleClass("active");
        } else {
            $(row.after('<tr class="content metadata active" ><td>something</td><td>something</td><td>something</td><td>something</td><td>something</td></tr>'));
        }
    });
});

Answer №1

To make the inserted row behave like a block element instead of a table-row, you need to change display:none to display:block. Additionally, ensure that you set display:table-row.

It's also important to add an empty first column to the new row to keep its columns aligned with the rows above.

Check out the code snippet below for more clarity:

$(document).ready(function() {
  $('body').on('click', 'table tr', function() {
    var row = $(this).closest('tr');
    if (row.next().hasClass("metadata")) {

      row.next().toggleClass("active");

    } else {
      $(row.after('<tr class="content metadata active" ><td></td><td>something</td><td>something</td><td>something</td><td>something</td><td>something</td></tr>'));

    }
  });
});
.metadata {
  display: none;
}

.metadata.active {
  display: table-row;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  margin-right: 20px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

td,
th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  text-align: left;
  padding: 8px;
  font-weight: normal;
}

th {
  text-decoration: none;
  font-size: 15px;
}

tr:nth-child(even) {
  background-color: #F5F5F5;
}

.content:hover {
  background-color: #99d1db;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table" style="text-align:center;">

  <table>
    <tbody>
      <tr>
        <th></th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>
        <th>blah</th>

      </tr>
      <tr class="content">
        <td>
          <input type="checkbox" name="tablebox" value="checker">
        </td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
        <td>blah</td>
      </tr>
    </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

Send an Ajax request to the controller and retrieve a file to display in an iframe

I need to display the contents of a byte[] array in an Iframe and provide the option for the user to download the file in PDF format. My view has a button connected to an ajax call that sends the byte[] to my actionresult, which returns a FileContentResul ...

Deactivate the button once the form has been submitted

Seems like a simple and common question, right? I also thought so. How can I achieve this in angularJS? CSHTML @using (Html.BeginForm("Order", "Shop", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { <div class="container" ng-ap ...

The clickable area on JQuery Tabs is not covering the entire surface

I'm having an issue with my JQuery tabs where the tab link does not work unless the mouse is directly over the text of the tab. It seems like the "li" element is being recognized instead of the link itself. I've searched for solutions, but most e ...

Is there a way to showcase English and CJK text vertically with CSS?

This particular issue was first discussed 14 years ago on Stack Overflow, but a definitive solution still remains elusive. My goal is to have both CJK and Latin characters displayed vertically, with their bottoms facing the right side. While writing-mode ...

Increase the number of file upload fields available for use

I've implemented this code to enable users to create additional upload fields. The fields are created successfully, and users can select a file. However, the selected file is not added to the input field except for the first one. On inspecting with fi ...

How come the color of the entire text within my HTML div is changing when I utilize Ajax and `$().css`?

Currently, I have a script that retrieves 4 attributes from a database table using Ajax and PHP. One of these attributes is the font color for the HTML output, which is stored in a variable called 'type'. My goal is to assign this font color to a ...

Ways to add margin-top to a card element without affecting the entire container-fluid

I'm attempting to change the background image of this container, but when I add margin-top to the card element, it shifts everything over the picture. Below is my Bootstrap4 code: #card.container-fluid { background-image: url("../images/picture2. ...

The jQuery .val() function does not function properly when using 'this'

This is an example with a textarea: <textarea id='ta' onkeydown='down(this)'></textarea> and here is the accompanying JavaScript code: <script> function down(input) { alert(input.val()); // not functioning ...

Press the Radio Button to automatically submit the form in ASP.Net Core

While working with ASP.Net Core, I encountered a scenario where I needed to update the page based on the radio button that a user clicks. I wanted the page to refresh automatically to display new data depending on the selected radio button. Would it be be ...

I seem to be having trouble with this JavaScript code. Could it be a syntax error, or is it possibly another issue causing it

I am encountering an issue with this code, as it is not functioning as intended. Although, I am unsure about the root of the problem. Code: <body> var randNumForQuote = Math.floor((Math.random() * 11)); if (randNumForQuote == 0) { docum ...

My CSS horizontal drop-down menu is causing the sub-navigation items to overlap each other

I'm having an issue where my sub navigation menu items are stacking on top of each other instead of displaying properly. Here is the code snippet causing the problem: /* STYLING FOR NAVIGATION MENU */ .nav-bar { width: 100%; height: 80px; ...

Alignment issues with images

I am trying to put together a collection of images that function as links and light up when hovered over. However, my attempt to add a <div class="hover"> in front of each image caused them to no longer display in a horizontal line. How can I resolve ...

Strategies for efficiently populating dropdown menus using a Load Saved Search feature

I have three dropdown boxes named marketOrg, region, and district which are populated using ajax calls. The market dropdown is filled when the page loads, and upon selecting a marketOrg from that dropdown, it triggers the getRegion() JavaScript function. T ...

The Harp server generates excessive white space within HTML documents

Running a blog on Harp has been smooth sailing, except for one issue that I can't seem to figure out. The project utilizes EJS and the problem lies in the outputted HTML containing excessive whitespace. I've attempted to minimize it, especially w ...

What is the best way to display HTML code that is stored as a string?

Hey there! I'm facing an issue with sending a string from MongoDB through res.render. When I check the sent string, it appears as just plain text instead of HTML, so I'm looking for a solution to fix this. router.get("/:id", async function (req, ...

Confirm the default value in a text box

I am currently working with a textbox that I have set up as shown below: <div form="form-group"> <label for="Title"> <h3>Title:</h3> </label> <div [ngClass]="{ 'has-errors': (dataProcessingEditFo ...

Rely on the content to establish the width, rather than the parent element

My elements include the following: .nav { width: 100%; background: red; display: flex; } .parent { background: blue; flex-grow: 1 } .child { background: yellow; } <div class="nav."> <div class="parent"> <div class="chi ...

Tips for choosing a particular value in an HTML <script> query

Can someone please help me figure out how to select specific values in a form using a query? I'm trying to extract certain values like Hello and Lorem ipsum..., as well as Hi and Nullam fringilla... from the Content.join(''); section. I apo ...

iOS is not receiving JSON data in the response headers

I am currently utilizing the CocoaHTTPServer for establishing my server connection. However, I encountered an issue with retrieving JSON data in the header file of my HTML page (web client). Here is the code snippet : HTML Page : endAPSession: funct ...

Styling a layout with two columns, centered with an offset

I have created a layout with two columns - one on the left and one on the right, with the left column containing two rows. However, I am looking to offset the center point of the column to the right so that the left column occupies about 60% of the space ...