Using a combination of CSS, Ajax, and jQuery, dynamically insert new rows into a table generated within a div

Apologies for the awkward question. I am currently working on a solution to create a table using div tags, which is functioning properly. However, I am facing an issue with adding or removing a row using jQuery. The problem lies in the fact that when a new row is added, it only populates the columns under "Header1". Despite my efforts to troubleshoot and resolve this issue, I have not been successful. I am reaching out here as my final attempt for assistance.

I have attempted to create a functional snippet, but unfortunately the "add new row" feature is not working here, although it does work in my browser..

$('#addrow').click(function(){
    var length = $('.sl').length;
    var i   = parseInt(length)+parseInt(1);
    var newrow = $('#next').append('<div class="divTableRow"><div class="divTableCell"><input type="text" class="form-control sl" name="slno[]" value="'+i+'" readonly=""></div><div class="divTableCell"><input type="text" class="form-control" name="name[]" id="acc_name'+i+'" placeholder="Enter Account Name" pattern="[^()/><\][\\\x22,;|]+"></div><div class="divTableCell"><select name="rang[]" id="rang_acc'+i+'" style="width:170px !important;font-weight: normal !important;" class="form-control"><option value="Bacteria">Bacteria</option><option value="Low Life">Low Life</option><option value="Apprentice">Apprentice</option><option value="Hitman">Hitman</option><option value="Assassin">Assassin</option><option value="Local Boss">Local Boss</option><option value="Boss">Boss</option><option value="Godfather">Godfather</option></select></div><div class="divTableCell"><input type="text" class="form-control" name="phone_no[]" id="pn'+i+'" placeholder="Enter Phone No"></div><div class="divTableCell"><input type="text" class="form-control" id="age'+i+'" name="...
    
});
    
// Removing event here
$('body').on('click','.btnRemove',function() {
   $(this).closest('div').remove()
});
div.blueTable {
    border: 1px solid #1C6EA4;
    background-color: #EEEEEE;
    width: 100%;
    text-align: left;
    border-collapse: collapse;
}
.divTable.blueTable .divTableCell, .divTable.blueTable .divTableHead {
    border: 1px solid #AAAAAA;
    padding: 3px 2px;
}
.divTable.blueTable .divTableBody .divTableCell {
    font-size: 13px;
}
.divTable.blueTable .divTableRow:nth-child(even) {
    background: #D0E4F5;
}
.divTable.blueTable .divTableHeading {
    background: #1C6EA4;
    background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    border-bottom: 2px solid #444444;
}
.divTable.blueTable .divTableHeading .divTableHead {
    font-size: 15px;
    font-weight: bold;
    color: #FFFFFF;
    border-left: 2px solid #D0E4F5;
}
.divTable.blueTable .divTableHeading .divTableHead:first-child {
    border-left: none;
}

.blueTable .tableFootStyle {
    font-size: 11px;
}
.blueTable .tableFootStyle .links {
    text-align: right;
}
.blueTable .tableFootStyle .links a{
    display: inline-block;
    background: #1C6EA4;
    color: #FFFFFF;
    padding: 2px 8px;
    border-radius: 5px;
}
.blueTable.outerTableFooter {
    border-top: none;
}
.blueTable.outerTableFooter .tableFootStyle {
    padding: 3px 5px; 
}
/* DivTable.com */
.divTable{ display: table; }
.divTableRow { display: table-row; }
.divTableHeading { display: table-header-group;}
.divTableCell, .divTableHead { display: table-cell;}
.divTableHeading { display: table-header-group;}
.divTableFoot { display: table-footer-group;}
.divTableBody { display: table-row-group;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<form class="form-horizontal" action="#" method="post">
    <div class="divTable blueTable">
        <div class="divTableHeading">
            <div class="divTableRow">
                <div class="divTableHead">head1</div>
                <div class="divTableHead">head2</div>
                <div class="divTableHead">head3</div>
                <div class="divTableHead">head4</div>
                <div class="divTableHead">head5</div>
                <div class="divTableHead">head6</div>
            </div>
        </div>
        <div class="divTableBody">
            <div class="divTableRow">
                <div class="divTableCell"&g...
            <div id="next"></div>
        </div>
    </div>
    <br/>
    <button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row</button>
    <br/><br/>
    <button type="submit" name="submit" class="btn btn-info pull-left">Submit</button>
</form>

Answer №1

  1. To include lengthy HTML strings, utilize backticks (`) for interpolation - this approach enables the creation of multi-line strings
  2. It is advisable to place (particularly long) HTML strings outside of your click handler. This will result in cleaner and more manageable code
  3. You mistakenly added the entire HTML string to #next instead of your table body container divTableBody
  4. There is a mismatch between the number of columns and cells being created
  5. By adding .parent() to your remove function, you have resolved the issue and it now functions correctly

const tableRow = (i) => {
  return `
    <div class="divTableRow">
      <div class="divTableCell">
        <input type="text" class="form-control sl" name="slno[]" value="${ i }" readonly="">
      </div>
      <div class="divTableCell">
        <input type="text" class="form-control" name="name[]" id="acc_name${ i }" placeholder="Enter Account Name" pattern="[^()/><\][\\\x22,;|]+">
      </div>
      <div class="divTableCell">
        <select name="rang[]" id="rang_acc${ i }" style="width:170px !important;font-weight: normal !important;" class="form-control">
          ...
        </select>
      </div>
      ...
      <div class="divTableCell">
        <input type="button" class="btnRemove btn-danger" value="Remove"/>
      </div>
    </div>
  `
}

$('#addrow').click(function() {
  var length = $('.sl').length;
  var i = parseInt(length) + parseInt(1);
  var newrow = $('.divTableBody').append(tableRow(i));
});

// Event handling for removal
$('body').on('click', '.btnRemove', function() {
  $(this).closest('div').parent().remove()
});
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<form class="form-horizontal" action="#" method="post">
  <div class="divTable blueTable">
    <div class="divTableHeading">
      <div class="divTableRow">
        <div class="divTableHead">head1</div>
        <div class="divTableHead">head2</div>
        <div class="divTableHead">head3</div>
        <div class="divTableHead">head4</div>
        <div class="divTableHead">head5</div>
        <div class="divTableHead">head6</div>
        <div class="divTableHead">head7</div>
      </div>
    </div>
    <div class="divTableBody">
      <div class="divTableRow">
        <div class="divTableCell">...</div>
        <div class="divTableCell">...</div>
        <div class="divTableCell">...</div>
        <div class="divTableCell">...</div>
        <div class="divTableCell">...</div>
        <div class="divTableCell">...</div>
      </div>
      <div id="next"></div>
    </div>
  </div>
  <br/>
  <button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row</button>
  <br/><br/>
  <button type="submit" name="submit" class="btn btn-info pull-left">Submit</button>
</form>

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

Tips for patiently waiting for an ajax request to complete before proceeding to the next task

I am currently facing a scenario where I need to handle multiple ajax requests. The URLs that I need to access are stored as strings in an array called listOfUrls. My goal is to make one ajax request, process the data, integrate it back into my applicatio ...

Retrieving text content from multiple classes with a single click event

There are numerous elements each having class names p1, p2, p3,...p14. Consequently, when attempting to extract text from the clicked class, text from all classes is retrieved! For instance, if the expected text is 80, it ends up being 808080080808080808 ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

Having trouble implementing font css file in Reactjs

When working with Reactjs (Nextjs), every time I try to incorporate "css" into my project, I encounter the following error on my screen: Module not found: Can't resolve '../fonts/fontawesome-webfont.eot?v=4.7.0' How can I solve this issue? ...

Transmit the Angular data model to the server

Whenever any of the inputs change, this function is triggered: $scope.updateOutputData = function(){ // Collecting input data and creating object $scope.selectionObject = { "departure_city" : departureCityDigest, "departure_country" : ...

A guide to implementing an analytics system by leveraging multiple applications

My front-end application, which runs on Rails 4 + Postgres, is referred to as FRONT_APP. I also have another application for statistics, running on Rails 4 + Mongodb, which is called STATISTICS_APP. Within my FRONT_APP, I utilize the following XHR query f ...

The JsonResult function is not being invoked when making an AJAX request

Here is the link to the JSON output: http://localhost:50028/Account/ Below is my JsonResult method: [HttpGet] public JsonResult GetGroupList() { try { DataConnection store = new DataConnection(); DataTable ...

I am looking to expand the width of the Bootstrap container specifically for the Max width

I need to adjust the width of the Bootstrap container to be responsive on all devices, especially maximizing the width on larger screens. Can anyone provide guidance on how to achieve this? Thank you in advance. To view my website, please follow this link ...

Tips for creating a transition effect when hovering over a CSS sprite

Below is a snippet of my CSS sprite code: #IconSet a { width: 36px; height: 36px; display: inline-block; } #DeviantArtIcon { border-width: 0px; border-style: none; background-image: url(http ...

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

How can I capture a Django "GET" event within a template using jQuery?

I have integrated a pdf download button in my Django project that generates a report. I want to display a modal indicating that the report is being processed when the button is clicked. Once the pdf is downloaded, I want the modal to automatically hide. H ...

Data is not added and shown in the collapsible feature of jQuery

I'm revisiting this topic and still haven't found a solution. a. Steps Taken: I constructed a query using PDO to retrieve information from the database using PHP, then I stored the results in an associative array and encoded it for transmission ...

Creating a responsive 'media object' in Bootstrap 4: Tips and tricks

I have a media object that displays an image with text next to it, and it looks good on larger screens. However, when I switch to a smaller screen, the text overflows and the images appear in different sizes and positions. <div class="container&quo ...

When using an HTML Select element with options loaded through Ajax, the desired item for selection is not being automatically selected

This is a strange situation. Collaborating with others and using sample code, I have created a routine that utilizes AJAX to pass a value from one select to a PHP file. The PHP file then generates a second select with options, each option designed to check ...

Tips on ensuring a div containing an image element has equal height as the image

Here is the HTML code I am working with: <div> <img src="http://placehold.it/319x300" alt=""> <div> And the corresponding CSS: *{margin: 0; padding: 0;} div{ background: red; width: 319px; height: auto; } img{ width ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Issues with Vue enter transitions not functioning as expected

I am currently involved in a project where I need to implement enter and exit animations for some components. When a component enters the screen, it should come from the bottom, and when it leaves, it should go upwards. The intended functionality is that w ...

Bootstrap side navigation bars are an essential tool for creating

Is there a way to change the hamburger icon in Bootstrap's navbar-toggle to an X button? I want the side nav to slide to the left when clicked, and also collapse when clicking inside the red rectangle. Thank you. https://i.sstatic.net/nQMGs.png Code ...

Access denied when trying to upload files on deployed Flask application using AJAX

After successfully implementing file upload functionality on the Flask server, I encountered an issue when deploying it on Apache2. The problem seems to arise when attempting to save the uploaded file. Below is the Python code using Flask: @app.route(&ap ...

Troubleshooting Issues with Ajax Functionality

I've been struggling with this ajax code that doesn't seem to be functioning as expected. It keeps returning the else statement instead of acknowledging a successful result. When I ran the dologin.php file, it did return 1 successfully. Thank you ...