skip to Main Content

Currently, I am creating a table that takes in first and last names. After filling out a row,I want a new row to appear (right now, I am just making a button so that I can get this functionality correct).

In this row, I want to create 2 cells that have text inputs inside which can be used for other names.

Question: How can I insert a text input into my HTML table rows and cells?

const table = document.querySelector('#table');

function lineMessage(msg) {
    document.querySelector('#myMessage').textContent += msg;
}

function groupMessage(msg) {
    document.querySelector('#myMessage').innerHTML += msg + '<br/>';
}

function addRow() {
    var row = table.insertRow(2);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "cell1";
    cell2.innerHTML = "cell2";
}
th {
    width: 50vmin;
    height: 10vmin;
    font-size: 20pt;
}

td {
    width: 50vmin;
    height: 5vmin;
}

input {
    width: 100%;
    height: 100%;
    text-align: center;
    align-items: center;
    font-size: 18pt;
    font-weight: 500;
    font-family: Georgia, 'Times New Roman', Times, serif;
    width: 100%;
    border: 0;
}

#submit {
    background-color: blue;
    color: white;
    border: 0;
    position: relative;
    left: 82vmin;
}

#myConsole {
    background-color: black;
    color: white;
    height: 25vmin;
}
<!DOCTYPE html>
<html lang="en">

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE-edge">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Christian Davis">
        <link rel="stylesheet" href="styles.css">
        <title>Random Group Generator</title>
    </head>

    <body>
        <table id="table" border="1">
            <tr>
                <th>First Name:</th>
                <th>Last Name:</th>
            </tr>

            <tr>
                <th><input type="text"></th>
                <th><input type="text"></th>
            </tr>
        </table> <br>

        <button onclick="addRow()">Add Row</button>
        <button id="submit">Submit</button>
        <p id="myConsole">&gt;&nbsp;<span id="myMessage"></span></p>
        <script src="app.js"></script>
    </body>
</html>

2

Answers


  1. If you meant that you want to add another row with inputs at the bottom of the table you can edit your addRow function into something like this:

    function addRow() {
        const row = table.insertRow(-1);
        
        const cell1 = row.insertCell(0);
        const cell2 = row.insertCell(1);
    
        const input1 = document.createElement("input");
        input1.type = "text";
        cell1.appendChild(input1);
    
        var input2 = document.createElement("input");
        input2.type = "text";
        cell2.appendChild(input2);
    }
    

    Please notice that In order to insert a row at the bottom of the table I used insertRow(-1)


    And this is the final result:

    const table = document.querySelector('#table');
    
    function lineMessage(msg) {
        document.querySelector('#myMessage').textContent += msg;
    }
    
    function groupMessage(msg) {
        document.querySelector('#myMessage').innerHTML += msg + '<br/>';
    }
    
    function addRow() {
        const row = table.insertRow(-1);
        
        const cell1 = row.insertCell(0);
        const cell2 = row.insertCell(1);
    
        const input1 = document.createElement("input");
        input1.type = "text";
        cell1.appendChild(input1);
    
        var input2 = document.createElement("input");
        input2.type = "text";
        cell2.appendChild(input2);
    }
    th {
        width: 50vmin;
        height: 10vmin;
        font-size: 20pt;
    }
    
    td {
        width: 50vmin;
        height: 5vmin;
    }
    
    input {
        width: 100%;
        height: 100%;
        text-align: center;
        align-items: center;
        font-size: 18pt;
        font-weight: 500;
        font-family: Georgia, 'Times New Roman', Times, serif;
        width: 100%;
        border: 0;
    }
    
    #submit {
        background-color: blue;
        color: white;
        border: 0;
        position: relative;
        left: 82vmin;
    }
    
    #myConsole {
        background-color: black;
        color: white;
        height: 25vmin;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <html>
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE-edge">
            <meta name="viewport", content="width=device-width, initial-scale=1.0">
            <meta name="author" content="Christian Davis">
            <link rel="stylesheet" href="styles.css">
            <title>Random Group Generator</title>
        </head>
    
        <body>
            <table id="table" border="1">
                <tr>
                    <th>First Name:</th>
                    <th>Last Name:</th>
                </tr>
    
                <tr>
                    <th><input type="text"></th>
                    <th><input type="text"></th>
                </tr>
            </table> <br>
    
            <button onclick="addRow()">Add Row</button>
            <button id="submit">Submit</button>
            <p id="myConsole">&gt;&nbsp;<span id="myMessage"></span></p>
            <script src="app.js"></script>
        </body>
    </html>
    Login or Signup to reply.
  2. There’s a few approaches, one is below with explanatory comments in the code:

    // I've removed the various functions that aren't used relevant to the problem,
    // and aren't used in the code posted here; if you're trying to solve a problem
    // it's best to try to remove irrelevant code while you're working on it (that
    // way you've got less code to sift through, and usually less scrolling through
    // the document(s):
    const table = document.querySelector('#table');
    
    // my personal preference is to declare functions as const variables, rather
    // than using the function declaration, and relying on hoisting so I'm commenting
    // this out, and doing that instead:
    /*
    function addRow() {
      var row = table.insertRow(2);
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      cell1.innerHTML = "cell1";
      cell2.innerHTML = "cell2";
      document.createElement("input");
    }
    */
    
    // using an Arrow function expression to define the function, and passing in a
    // reference to the Event Object that triggered the function call:
    const addRow = (evt) => {
      // here we need to create a table row with two table cells and in those cells
      // create a single <input>, so:
      let tr = document.createElement('tr'),
        td = document.createElement('td'),
        input = document.createElement('input');
        
      // the default type of an <input> element is "text", but I prefer to be
      // explicit, and set that in the code:
      input.type = "text";
      
      // here we append the created <input> to the <td>:
      td.append(input);
      
      // here we append the <td>, along with a clone of that <td> to the <tr>:
      tr.append(td, td.cloneNode(true));
      
      // if the author doesn't define a <tbody> element to wrap the contents,
      // all browsers (so far as I've worked with so far) automatically do so;
      // so here we retrieve the <tbody> descendant of an element with the id
      // of "table", and append the <tr> to that element:
      document.querySelector('#table tbody').append(tr);
    }
    
    document.querySelector('.addRow').addEventListener('click', addRow);
    th {
      width: 50vmin;
      height: 10vmin;
      font-size: 20pt;
    }
    
    td {
      width: 50vmin;
      height: 5vmin;
    }
    
    input {
      width: 100%;
      height: 100%;
      text-align: center;
      align-items: center;
      font-size: 18pt;
      font-weight: 500;
      font-family: Georgia, 'Times New Roman', Times, serif;
      width: 100%;
      border: 0;
    }
    
    #submit {
      background-color: blue;
      color: white;
      border: 0;
      position: relative;
      left: 82vmin;
    }
    
    #myConsole {
      background-color: black;
      color: white;
      height: 25vmin;
    }
    <table id="table" border="1">
      <tr>
        <th>First Name:</th>
        <th>Last Name:</th>
      </tr>
    
      <tr>
        <!-- a <th> is a table-heading element, whereas the <input> elements are part of
             the content, and so should appear in <td> (table-data) cells: --> 
        <td><input type="text"></td>
        <td><input type="text"></td>
      </tr>
    </table>
    
    <br>
    
    <!-- don't use event attributes in the HTML where possible, using JavaScript to bind
         the JavaScript event-handlers is usually makes the resulting code easier to maintain,
         here I've removed the "onclick" attribute, and added a class-name (this isn't
         strictly necessary, but it's an easier method to demonstrate) by which the event-handler
         can be bound: -->
    <button class="addRow">Add Row</button>
    <button id="submit">Submit</button>

    There are other ways, though; one of which is to simply clone the existing elements, as shown below:

    const addRow = (evt) => {
      // caching a reference to the <tbody> element:
      let tbody = document.querySelector('#table tbody'),
          // looking within the <tbody> element to retrieve the last
          // element child node, and cloning it (including its content):
          clone = tbody.lastElementChild.cloneNode(true);
      
      // here we use Element.querySelectorAll() to find all <input> elements:
      clone.querySelectorAll('input')
        // using NodeList.prototype.forEach() in order to iterate through
        // the NodeList:
        .forEach(
          // 'el' is a reference to the current Node of the NodeList,
          // and here we set the value of the element to its default-value
          // in order that the user-entered value isn't copied, and the
          // <input> returns to the normal "base-state" in which it
          // appeared on page-load:
          (el) => el.value = el.defaultValue
        )
        
      // appending the cloned <tr> (and its content) to the <tbody>:
      tbody.append(clone);
    }
    
    // selecting the first/only element matching the supplied CSS selector:
    document.querySelector('.addRow')
      // using EventTarget.addEventListener() to bind the addRow function
      // as the event-handler for the 'click' event:
      .addEventListener('click', addRow);
    th {
      width: 50vmin;
      height: 10vmin;
      font-size: 20pt;
    }
    
    td {
      width: 50vmin;
      height: 5vmin;
    }
    
    input {
      width: 100%;
      height: 100%;
      text-align: center;
      align-items: center;
      font-size: 18pt;
      font-weight: 500;
      font-family: Georgia, 'Times New Roman', Times, serif;
      width: 100%;
      border: 0;
    }
    
    #submit {
      background-color: blue;
      color: white;
      border: 0;
      position: relative;
      left: 82vmin;
    }
    
    #myConsole {
      background-color: black;
      color: white;
      height: 25vmin;
    }
    <table id="table" border="1">
      <thead>
        <tr>
          <th>First Name:</th>
          <th>Last Name:</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type="text"></td>
          <td><input type="text"></td>
        </tr>
      </tbody>
    </table>
    
    <button class="addRow">Add Row</button>
    <button id="submit">Submit</button>

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search