I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
Related
I thought maybe doing this with a for loop like that
<table>
<script>
for (var i; i = 0; i < 8; i++) {
document.write("<tr>")
for (var j; j = 0; j < 8; j++) {
document.write("<td></td>")
}
document.write("<tr>")
}
</script>
</table>
This code doesn't seem to work. Please understand that I am not at all fluent in js, so a solution with an explenationn will really help.
document.write would not work as you have tried here, it won't write the <tr> tags at the place you've mentioned either.
You need to modify the DOM, specifically the table element.
Below code, takes a reference of table and appends the 8 rows and 8 cols in it.
document.querySelector("table").innerHTML = new Array(8).fill("<tr>" + new Array(8).fill("<td></td>").join("") + "</tr>").join("");
td {
border: 1px solid;
padding: 5px;
}
<table></table>
PS: This is a basic example to get you started, there are better ways to achieve this. you should look more into DOM Manipulation in JS.
Use DOM manipulation methods and make sure to put <script> right before the closing tag of <body> instead of inside <tabl> , here is a working example:
let table = document.getElementById('table');
for (let i = 0; i < 8; i++) {
let row = document.createElement('TR');
table.appendChild(row);
for (let i = 0; i < 8; i++) {
var cell = document.createElement('TD');
row.appendChild(cell);
}
}
td {
border: 1px solid #333;
padding: 5px;
}
<table id="table"></table>
document.write() will never create a child element inside the <table> element, you can create a child element for a parent with appendChild().
Here an example with pure JavaScript:
for (var i = 0; i < 8; i++) {
var row = document.createElement("tr");
document.getElementById('tbl').appendChild(row).setAttribute("id", 'row_' + i);
for (var j = 0; j < 8; j++) {
var column = document.createElement("td");
document.getElementById('row_' + i).appendChild(column);
}
}
table {
border: 1px solid black;
}
td {
border: 1px solid blue;
padding: 3px;
margin: 2px;
}
<table id='tbl'></table>
Here, the script will create a child <tr> for the <table>, then you can create child <td> for the <tr>.
I am creating a table that creates tr's and td's within a table. The table with loop through a subtraction calculation and create a column of the results from the for loop. When I try to add the next column it does not parse the calculations but continues to perform calculations
for (i=foo; i<bar+1; i++)
{
var tableNode = document.getElementById('tableID');
var trNode = document.createElement('tr');
var trValue = '';
var tdNode = document.createElement('td');
var tdValue = parseFloat(i) + parseFloat(500); //this is calculating 500 and not concatenating 500 for every iteration.
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
tableNode.appendChild(trNode);
trNode.appendChild(tdNode);
}
The goal is to do using a for loop that populates the tr's and td's
1 500
2 500
3 500
This should work:
let foo = 1,
bar = 3;
for (let i = foo; i <= bar; i++) {
var tableNode = document.getElementById("tableID");
let trNode = document.createElement("tr");
let trValue = "";
let tdNode = document.createElement("td");
let tdValue = parseFloat(i) + ' ' + parseFloat(500);
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
trNode.appendChild(tdNode);
tableNode.appendChild(trNode);
}
table tr td {
border: 1px solid #ccc;
}
<table id="tableID"></table>
If you want to concatenate parseFloat(i) and parseFloat(500), do:
var tdValue = parseFloat(i) + " " + parseFloat(500);
instead of parseFloat(i) + parseFloat(500) because this will add the float values and tdValue will be the sum (of type number).
Note the " " (string containing a space) in the middle which will consider the elements to be concatenated as strings and the result of the concatenation to be of type string.
<table> & for loops
If you want to generate a <table> with a for loop you should use two for loops -- first loop is for rows and the second loop is for cells for each row. The following demo has the following:
A <form> that has:
An <input> to enter the number of rows.
An <input> to enter the number of cells per row.
button to trigger the click event that calls the function generateTable().
The <form> and all of its form controls are accessed by using HTMLFormControlsCollection API.
The methods .insertRow() and .insertCell() will automatically create an element and append it.
The <form> and all that's related to it are optional of course, it's just added for demonstration purposes. The loops can be used alone by just assigning numbers to variables rowQty and celQty.
Demo
/*
Optional
*/
var ui = document.forms[0].elements;
var btn = ui.btn;
btn.onclick = generateTable;
/*
Required
*/
function generateTable(e) {
var table = document.getElementById('T0');
/*
if used without the <form>
replace the next two lines with:
*/
//var rowQty = {any integer}
//var celQty = {any integer 2 or greter}
var rowQty = ui.rowData.value;
var celQty = ui.celData.value;
for (let i = 0; i < rowQty; i++) {
var tr = table.insertRow(i);
for (let j = 0; j < celQty; j++) {
var td = tr.insertCell(j);
if (j === 0) {
td.textContent = i + 1;
} else if (j === 1) {
td.textContent = "500";
} else {
td.textContent = " ";
}
}
}
}
table {
border-collapse: collapse;
table-layout: fixed;
}
table,
td {
border: 1px solid #000;
text-align: right;
}
td {
min-width: 3ch;
max-width: 150px;
}
td:first-of-type {
width: 3ch;
text-align: center;
}
input {
display: inline-block;
text-align: center;
width: 5ch;
}
<!-- Optional -->
<form id='ui'>
<label for='rowData'>Rows: </label>
<input id='rowData' type='number' min='1' max='10' value='1'>
<label for='celData'>Cells per Row: </label>
<input id='celData' type='number' min='2' max='10' value='2'>
<button id='btn' type='button'>GO</button>
</form>
<!-- Required -->
<table id='T0'></table>
This question already has answers here:
How to put text inside radio button?
(2 answers)
Closed 5 years ago.
I was wondering if there was a way to add a placeholder to a radio button. I tried to do it, code below, but it did not work. I want the first button to have the placeholder value "1", and the second to have the value "2" and so on. Is there a way to do that? I mean that the button, when the user looks at it, will have number "1" in it.
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.getElementById("table");
table.innerHTML = "";
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 7 && cellsToDraw > 0; c++) {
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("placeholder", 1)
newRow.appendChild(newCell);
newCell.innerHTML = //add the numbers here?
cellsToDraw--;
}
}
}
CSS:
input[type=radio] {
border: 1px solid;
padding: 0.5em;
-webkit-appearance: none;
width: 95px;
height: 100px;
margin-right: -4px;
margin-top: -8px;
}
All help is appriciated!
Radio buttons don't support placeholders, and there wouldn't be any space to render one in anyway.
It sounds like you are confusing placeholders with labels (see this article).
Use a LABEL element instead.
Aside: INPUT elements are not allowed to be children of TR elements. Only TD and TH elements may be children of a TR.
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.createElement("table");
document.body.appendChild(table);
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 7 && cellsToDraw > 0; c++) {
var newCell = document.createElement("td");
var input = document.createElement("input");
var label = document.createElement("label");
input.setAttribute("type", "radio");
input.setAttribute("name", "day");
label.appendChild(input);
label.appendChild(document.createTextNode("1"));
newCell.appendChild(label);
newRow.appendChild(newCell);
cellsToDraw--;
}
}
}
drawTable(30);
instead of innerHTML you can set value
newCell.value = c
This is JavaScript HTML table generator.
Input (from textarea)
<label> <content> //each line
Order by <label>
I need to input the values like that:
Input Values
or
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
And the output should be :
Example
Here is the problem. I don't have ideas to finish my work, but i try my best to code.Can anyone help me?Please!!
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
// CODE START
// CODE END
}
var out="<table>"; // if the value exist, using table to display
// CODE START
// CODE END
out=out+"</table>"
document.getElementById('out').innerHTML=out; // display the result
}
And the html code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> HW3 </title>
<script type="text/javascript" src="abc.js"></script>
<style type = "text/css">
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td
{
border:1px solid black;
}
</style>
</head>
<body>
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
</body>
</html>
I have create sample based on your requirement.
Please check this code.
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
var uniqueValue = [];
var values = [];
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
if (uniqueValue.indexOf(seq[0]) == -1)
{
uniqueValue.push(seq[0]);
values[uniqueValue.indexOf(seq[0])] = new Array();
}
values[uniqueValue.indexOf(seq[0])].push(seq[1]);
}
var maxLength = 0;
var length = values.length;
for (i = 0; i < length; i++)
{
if(values[i].length > maxLength)
maxLength = values[i].length
}
if (length > 0)
{
var out = "<table>"; // if the value exist, using table to display
for (var i = 0; i <= maxLength; i++)
{
out = out + "<tr>"
for (var j = 0; j < length; j++)
{
if(i==0)
{
out = out+ "<th>"+ uniqueValue[j] +"</th>";
}
else
{
if (values[j][i - 1])
out = out + "<td>" + values[j][i - 1] + "</td>";
else
out = out + "<td></td>";
}
}
out = out + "</tr>"
}
out = out + "</table>"
}
document.getElementById('out').innerHTML=out; // display the result
}
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td, tr th
{
border:1px solid black;
}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
Hope this will help you.
I gave it a try too. This approach should give you the big idea behind the dynamically created DOM elements. I think this is a more production-friendly version of the algorithm, given that only native JS is being used.
The main difference with my approach is that it works entirely with dynamic DOM Elements to build the table instead of static html markup. In some cases it can be easier to read and more flexible, especially if you want to work with tag attributes dynamically. I also managed to reduce the complexity by 1 level. Here's my try at it to make it simple and readable:
document.getElementById("btn").addEventListener("click", function(event) {
progress();
}, false);
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
// Build label->content association
var inputs = {};
for (var i = 0; i<line_num; i++)
{
if (line[i] != "") {
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
var label = seq[0];
var content = seq[1];
if (inputs[label] === undefined) {
inputs[label] = [content];
} else {
inputs[label].push(content);
}
}
}
// For a given MxN table output
var M = Object.keys(inputs).length;
var N = 0; // Unknown for now
var tableElement = document.createElement("table");
tableElement.id = "out";
// Generate header
var headerElement = document.createElement("tr");
for (var label in inputs) {
var tdElement = document.createElement("td");
tdElement.appendChild(document.createTextNode(label));
headerElement.appendChild(tdElement);
// calculate N dimension
var contents = inputs[label].length;
if (N < contents) {
N = contents;
}
}
tableElement.appendChild(headerElement);
// Generate rows
for (var i=0; i<N; i++) {
var trElement = document.createElement("tr");
for (var j=0; j<M; j++) {
var tdElement = document.createElement("td");
var label = Object.keys(inputs)[j];
if (inputs[label].length > i) {
var content = inputs[label][i];
tdElement.appendChild(document.createTextNode(content));
}
trElement.appendChild(tdElement);
}
tableElement.appendChild(trElement);
}
var out = document.getElementById('out');
out.parentNode.removeChild(out);
document.body.appendChild(tableElement); // display the result
}
table {border-collapse:collapse;}
tr,td {border:solid 1px #000;}
td {width:100px;}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label>
<textarea name="txt" rows="20" cols = "40">
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
</textarea>
</label>
<br>
<button id="btn" type="submit">Submit</button>
</form>
<p id= "out"></p>
Hope this helps.
Have a nice one!
Im making a blackjack game for an assignment and have arrays for leaderboard and cards.
I want to print the leader board like this. CARDS(in individual cells)| TOTAL.
help would be appreciated, thanks
function makeTable(leaderBoard) {
var table = document.createElement('table');
for (var i = 0; i < leaderBoard.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < leaderBoard[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.getElementById('leaderBoard').innerHTML = table;
}
Maybe the example input isn't in the correct format, but reusing a predefined table and html table functions such as insertRow and insertCell (not necessarily better, but they can be easier on the eye than createElement and append) :
<div id="leaderBoard"><table id=leaderTable></table></div>
function updateleaderboard(leaderBoard) {
var table = document.getElementById('leaderTable');
while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any
for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
var row =table.insertRow();
var arrCards = leaderBoard[i++];
var total = row.insertCell();
total.className = 'res';
total.textContent = leaderBoard[i];
arrCards.forEach(function(c,ind){
row.insertCell(ind).textContent = c;
});
}
}
var cards = [['Q','4','5'],19];
updateleaderboard(cards);
Fiddle
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
http://jsfiddle.net/25kg3nnq/