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">> <span id="myMessage"></span></p>
<script src="app.js"></script>
</body>
</html>
2
Answers
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: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:
There’s a few approaches, one is below with explanatory comments in the code:
There are other ways, though; one of which is to simply clone the existing elements, as shown below:
References:
document.querySelector()
.document.querySelectorAll()
.Element.append()
.Element.lastElementChild()
.Element.querySelector()
.Element.querySelectorAll()
.EventTarget.addEventListener()
.Node.cloneNode()
.NodeList
forEach()
method.