Dynamically Insert a Row into a Table using Bootstrap and JavaScript

Can someone provide assistance with my code? Specifically, I am looking to add the index number whenever a user clicks the add button and would like to know how to insert text input similar to the first row. I am currently in the process of learning JavaScript. Thank you in advance!

function appendRow() {
  var table = document.getElementById("childTable");
  var row = table.insertRow(2);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var cell4 = row.insertCell(3);
  var cell5 = row.insertCell(4);
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7f7272696e696f7c6d5d28332d332c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

<table class="table table-bordered" id="childTable">
  <thead class="table-info">
    <tr>
      <th scope="col">No.</th>
      <th scope="col">Name</th>
      <th scope="col">School / University </th>
      <th scope="col">Year</th>
      <th scope="col">Age</th>
      <th scope=""></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td class="col-sm-4">
        <input type="text" name="name" class="form-control" />
      </td>
      <td>
        <input type="text" name="school" class="form-control" />
      </td>
      <td class="col-sm-2">
        <input type="text" name="year" class="form-control" />
      </td>
      <td class="col-sm-2">
        <input type="text" name="age" class="form-control" />
      </td>
      <td>
        <input type="button" class="btn btn-block btn-default" id="addrow" onclick="appendRow()" value="+" />
      </td>
    </tr>
  </tbody>
</table>

Answer №1

Take a look at this code.....

var i = 1;
function addChildRow() {
  i++;
  $('#childTable').find('tbody').append('<tr><th scope="row">'+i+'</th><td class="col-sm-4"><input type="text" name="name" class="form-control" /></td><td><input type="text" name="school" class="form-control" /></td><td class="col-sm-2"><input type="text" name="year" class="form-control" /></td><td class="col-sm-2"><input type="text" name="age" class="form-control" /></td><td><input type="button" class="btn btn-block btn-default" id="addrow" onclick="addChildRow()" value="+" /></td></tr>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096b66667d7a7d7d765a7f76716e6f61717e156265">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

<table class="table table-bordered" id="childTable">
  <thead class="table-info">
    <tr>
      <th scope="col">No.</th>
      <th scope="col">Name</th>
      <th scope="col">School / University </th>
      <th scope="col">Year</th>
      <th scope="col">Age</th>
      <th scope=""></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td class="col-sm-4">
        <input type="text" name="name" class="form-control" />
      </td>
      <td>
        <input type="text" name="school" class="form-control" />
      </td>
      <td class="col-sm-2">
        <input type="text" name="year" class="form-control" />
      </td>
      <td class="col-sm-2">
        <input type="text" name="age" class="form-control" />
      </td>
      <td>
        <input type="button" class="btn btn-block btn-default" id="addrow" onclick="addChildRow()" value="+" />
      </td>
    </tr>
  </tbody>
</table>

Answer №2

Substitute your current function with the function provided below

 function removeTableRow(id)
{
document.getElementById(id).remove()
}

function addNewTableRow() {

  var table = document.getElementById("childTable");
  // FIND TOTAL NUMBER OF ROWS 
  var totalRows = table.rows.length;
  var newId = "tbl" + totalRows;
  var newRow = table.insertRow(totalRows);
  newRow.id = newId;
  var cell1 = newRow.insertCell(0);
  var cell2 = newRow.insertCell(1);
  var cell3 = newRow.insertCell(2);
  var cell4 = newRow.insertCell(3);
  var cell5 = newRow.insertCell(4);
  var cell6 = newRow.insertCell(5);
  cell1.outerHTML = `<th> ${totalRows}</th>`;
  cell2.innerHTML = ' <input type="text" name="name" class="form-control" />';
  cell3.innerHTML = ' <input type="text" name="school" class="form-control" />';
  cell4.innerHTML = ' <input type="text" name="year" class="form-control" />';
  cell5.innerHTML = ' <input type="text" name="age" class="form-control" />';
  cell6.innerHTML = '  <input type="button" class="btn btn-block btn-default" id="addrow" onclick="removeTableRow(\''+newId+'\')" value="Delete" /> '; 
}

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

"Looking to disable the browser shortcut for ctrl-N and instead trigger a function when this key combination is pressed? Check out the JS Fiddle example provided below

I recently incorporated the library shortcut.js from In my project, I attempted to execute a function when CTRL + N is pressed. The function executed as expected; however, since CTRL + N is a browser shortcut for opening a new window in Mozilla 8, it also ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Can anyone provide guidance on how to make slideToggle move upwards with jQuery?

<div class="row"> <div class="col-lg-2" ></div> <div class="head" style="background-color: #1c94c4; text-align: center; cursor: pointer;"> Connect</div> <div class="chat" style="display: none;width:a ...

Unable to retrieve class attributes within a function

I have recently started delving into the world of node.js, and I am facing some challenges with a middleware that I created. The purpose of this middleware is to act as an Error handler. However, I am encountering difficulties in accessing properties that ...

Using JQuery to create an animated slideToggle effect for a multicolumn list

I have a large list where each li element has a width of 33%, resulting in 3 columns: computers monitors hi-fi sex-toys pancakes scissors Each column contains a hidden UL, which is revealed through slideToggle on click. JQuery $('.subCate ...

utilizing vue model attributes with `${}`

I am encountering an issue with my code. Initially, :src="labels[index]" was working fine for me. However, as my codebase expanded, I needed to use ${app.labels[index]}. Simply using ${app.labels} works, but the addition of [index] causes it to b ...

Discover the steps to download web page data using Objective-C while ensuring that JavaScript has finished executing

I attempted something similar: NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *error = nil; NSString *htmlContent = [NSString stringWithContentsOfURL:urlrequest encoding:NSUTF8StringEncoding error:&e ...

Attempting to input information into my complex relationship structure

Currently, I am experiencing an issue with merging an old guardian with a new student in my pivot table that stores Student and guardian relationships. The process involves creating a student first before adding a guardian. Each entity has its own table an ...

"Learn the steps to seamlessly add text at the current cursor position with the angular-editor tool

How can I display the selected value from a dropdown in a text box at the current cursor position? I am currently using the following code: enter code selectChangeHandler(event: any) { this.selectedID = event.target.value; // console.log("this.selecte ...

Where am I going wrong in my attempts to use a callback function?

I am currently attempting to implement a callback function for this particular JavaScript function. function Filtering_GetSite(siteElement) { $.ajax({ type: "POST", url: "samle.asmx/f1", data: "", contentType: "application/json; charset= ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Querying with Laravel - Finding records based on a list of numbers

I am working with a query that looks like this: $vlsalesitemid="11,12,13," $query=DB::table('st_temp_sales')->where('brand_id', $brandid) ->whereIn($vlsalesitemid) ...

How to customize a dropdown menu with the size property?

Can anyone help me with styling a select box that uses the size attribute? Most tutorials only cover single-item select boxes. Has anyone dealt with styling select boxes with the size attribute before? Here's an example of what I'm trying to acc ...

Customize your Android WebView to show specific sections of a website

Struggling to display a specific part of a webpage in my webview, despite trying numerous solutions. https://i.sstatic.net/b185H.png class ActionFragment : Fragment() { class MyWebClient : WebViewClient() { override fun shouldOverrideUrlLoadin ...

Transform an array into an array of objects using the reduce method

optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore'] result = [ {start: bengaluru, end: salem}, {start: salem, end: erode}, {start: erode, end: tiruppur}, {start: tiruppur, en ...

Ways to handle a hidden element in Selenium Webdriver

Special features of this element:- <textarea id="txtSuffixTitle" class="form-control" tabindex="3" rows="2" placeholder="Suffix Title" name="txtSuffixTitle" maxlength="50" cols="20" style="display: none; visibility: hidden;">Suffix Title </text ...

React Native's 'onMessage' feature is currently experiencing issues and is not functioning

I'm attempting to retrieve the content of a URL by sending a post message and then listening for it using onMessage, but unfortunately it does not seem to be functioning properly. render(){ const getHtmlJS = "window.postMessage(document.getElementsBy ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...

Spin: twist beyond 360 degrees or less than 0 degrees

Attempting to rotate an arrow indicating wind direction using the transform: rotate() property. The data for rotation is retrieved from an API fetch, and conventional measurement of wind direction involves indicating where the wind is coming from. Therefo ...