6

Working with HTML5, I have created a simple table that consists of a series of pair fields (Activity log, time). I've been searching on the web how to dynamically create fields using Javascript, but I've only found how to create one field at a time (using getElementById). The thing is that I'd like to create a series of tags. Meaning, when the user clicks on "add another field", I'd like that JS to generate another row on the table, with a pair of fields, instead of having to hard code the complete table (the snippet below only has two rows, but I'd probably need 10-15 rows).

The snippet of the code for the table appears below. Using CSS the page looks as it's on the screenshot. screenshot

I'd appreciate any help. Thanks in advance.

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="utf-8">
   <title>Activity Log</title>
   <link href="styles.css" rel="stylesheet">
   <script type="text/javascript" language="javascript" src="script.js"></script>

</head>

<body>
<div class="container">
    <div class="row">
        <div class="leftcol">
            <form name='mainForm' id='mainForm' method="get" action="http://www.randyconnolly.com/tests/process.php">
  <fieldset>
     <legend>Input Activity Logs</legend>
     <table id=tracklist>
      <tr>
        <th colspan="3">Track List: </th>
      </tr>
      <tr>
        <td>1</td>
        <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
        <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
      </tr>
      <tr>
        <td>2</td>
        <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
        <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
      </tr>
     </table>
     <input type="submit" />
  </fieldset>
</form>
        </div>

    </div>
</div>
</body>
</html>
ZSmain
  • 266
  • 1
  • 4
  • 18
Emilio Zaidman
  • 107
  • 1
  • 1
  • 7

6 Answers6

4

Some popular ways to add element:

  1. Use document.createElement to create element you need, and use document.appendChild or document.insertBefore to add it to html.
  2. Use element.insertAdjacentHTML to add element.
  3. Use libraries like jQuery and React.
L_K
  • 2,600
  • 1
  • 13
  • 34
3

You can use the .innerHTML += method wired up to an "Add Activity" button. Each time you click the button a new table row is added with the correct index numbers. Here is a fully working example - for the sake of simplicity and having only one file, I've included the javascript directly in the HTML code:

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="utf-8">
   <title>Activity Log</title>
   <script>

      // Wait until the window finishes loaded before executing any script
      window.onload = function() {

        // Initialize the activityNumber
        var activityNumber = 3;

        // Select the add_activity button
        var addButton = document.getElementById("add_activity");

        // Select the table element
        var tracklistTable = document.getElementById("tracklist");

        // Attach handler to the button click event
        addButton.onclick = function() {

        // Add a new row to the table using the correct activityNumber
          tracklistTable.innerHTML += '<tr><td>' + activityNumber + '</td><td><label>Activity Log: </label><br/><input type="text" name="actlog' + activityNumber + '" class="required"></td><td><label>Time: </label><br/><input type="time" name="time' + activityNumber + '" class="required"></td></tr>';

          // Increment the activityNumber
          activityNumber += 1;
        }

      }

   </script>

</head>

<body>
  <div class="container">
      <div class="row">
          <div class="leftcol">
              <form name='mainForm' id='mainForm' method="get" action="#">
                <fieldset>
                   <legend>Input Activity Logs</legend>
                   <table id="tracklist">
                    <tr>
                      <th colspan="3">Track List: </th>
                    </tr>
                    <tr>
                      <td>1</td>
                      <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
                      <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
                    </tr>
                    <tr>
                      <td>2</td>
                      <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
                      <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
                    </tr>
                   </table>
                   <input type="submit" />
                </fieldset>
              </form>
              <button id="add_activity">Add Activity</button>
          </div>
      </div>
  </div>
</body>
</html>
2

Add a button like <input type="button" onclick="cloneRow()" value="Clone Row" /> in your html and add a id to the row to be copied (exm. <tr id="rowToClone">) then add the following javascript function in your code

 function cloneRow() {
     var row = document.getElementById("rowToClone"); // find row to copy
     var table = document.getElementById("tracklist"); // find table to append to
     var clone = row.cloneNode(true); // copy children too
     clone.id = "newID"; // change id or other attributes/contents
     table.appendChild(clone); // add new row to end of table
 }
Hector Barbossa
  • 5,330
  • 13
  • 47
  • 70
1

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  strHtml="<h1>hello</h1>"

  constructor() { }

  ngOnInit(): void {
  }
  insert(){
    let tag = document.getElementById("main");
    let text = document.createElement("H1");
    text.innerHTML = "new string element";
    tag.appendChild(text);
  }

}
<div class="container pt-3 mx-auto">
    <div id="main" [innerHtml]="strHtml"></div>
    <button class="btn btn-primary mt-4" (click)="insert()">New</button>
</div>
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – jasie Nov 26 '20 at 13:44
0

What you need is document.createElemrnt(tagNameString); That function does exactly what you think. Then you can create more elements and make them children of another.

Richard Barker
  • 1,101
  • 2
  • 12
  • 30
0

Syntax is here:

`<span> ${data.d.name}</span>`
babak
  • 1
  • 1
  • 1