Set type text inside cell javascript - javascript

I want to type text inside the cell but I tried to set attribute with td but it doesn't work. Please help me how can I set attribute to type text in the cell. Thank you for your help!
function addTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();

You need to create an input element and then append that to td:
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns", 1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', 'text');
td.appendChild(input);
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
<div id="myDynamicTable">
</div>

You can use contenteditable attribute: td.contenteditable = 'true';.
Depending on how you want to use this value, you might also insert an input element.

You are perhaps looking for contentEditable?
function addTable() {
const rn = +window.prompt("Input number of rows", 1);
const cn = +window.prompt("Input number of columns", 1);
const myTableDiv = document.getElementById("myDynamicTable");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (let i = 0; i < rn; i++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (let j = 0; j < cn; j++) {
var td = document.createElement('td');
td.width = '75';
td.contentEditable = true;
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>

if you want to operate on tables, use corrects javascript instructions ...
const
DynTb = document.getElementById('myDynamicTable')
rn = +window.prompt("Input number of rows", 1)
, cn = +window.prompt("Input number of columns", 1)
;
if( isNaN(rn) || isNaN(cn))
throw 'bad integer input value (s)'
const myTable = addTable(DynTb, rn, cn )
function addTable(tDiv, rn, cn)
{
let
tab = tDiv.appendChild( document.createElement('table') )
, tBy = tab.createTBody()
;
for(let r=0;r<rn;++r)
{
let row = tBy.insertRow()
for(let c=0;c<cn;++c)
{
row.insertCell().innerHTML =
`<input type="text" placeHolder="${r}-${c}">`
} }
return tab
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td {
padding : .2em;
border : 1px solid darkblue;
}
input {
width : 5em;
}
<div id="myDynamicTable"></div>

Related

Displaying javascript data in html after retrieving it from mysql [duplicate]

I need your help,
For some reason, I can't get the data captured in my array to populate into the TD cells of my dynamically generated table:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "Request Type"
heading[1] = "Group A"
heading[2] = "Groub B"
heading[3] = "Group C"
heading[4] = "Total"
var stock = new Array()
stock[0] = new Array("Cars", "88.625", "85.50", "85.81", "987")
stock[1] = new Array("Veggies", "88.625", "85.50", "85.81", "988")
stock[2] = new Array("Colors", "88.625", "85.50", "85.81", "989")
stock[3] = new Array("Numbers", "88.625", "85.50", "85.81", "990")
stock[4] = new Array("Requests", "88.625", "85.50", "85.81", "991")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < stock.length; i++) {
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td)
}
}
myTableDiv.appendChild(table)
}
</script>
</head>
<div id="metric_results">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
</div>
</body>
</html>
Change:
var tr = document.createElement('TR'); // this should be inside the first loop
tableBody.appendChild(tr); // this should be just before the first loop is over
for (i=0; i<stock.length; i++) {
for (j=0; j<stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td) // this should be tr.appendChild(td)
}
}
to this:
for (i = 0; i < stock.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
Fiddle

How can i insert a label text in a table cell

I have a table which i am dynamically generating based on user input. I am trying to insert a label text into table cell on button click. onclick of button a label text of a demo method should be inserted into table cells. Can someone suggest me how can i do this?
Thanks.
Creating Table:
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Button:
<asp:Button ID="button1" Text="button" runat="server" OnClick="demo" />
C# code:
public void demo()
{
TableCell tcell = new TableCell();
RadLabel rlbl = new RadLabel();
rlbl.Text = "test";
tcell.Controls.Add(rlbl);
}
protected void demo(object sender, EventArgs e)
{
demo();
}
To give you a start using Javascript, you can use below code as a starting point.
window.onload=function(){
CreateTable();
}
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = 3; //document.getElementById('txtrows').value;
cellCnt =2; //document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function demo(){
var myTable=document.getElementById('myTable');
var cell=myTable.rows[0].cells[1];
var label = document.createElement('label');
label.id="lbl-"+cell.cellIndex;
label.innerText="This is label text";
cell.appendChild(label);
}
<input type="button" onclick="demo()" value="Create Label" />
<div id="myDynamicTable"></div>

Dynamically created table only displays last appended table data

I am working with Javascript where I've got a drop down list derived from an array (List of stream names) and whenever this array selection changes (onchange()) the details of the array( attributes and types) should be derived from two arrays (two 1d arrays- attributes, type) and displayed in a table form below the dropdown. I've written the function that displays the table within a division but it retrieves only the last data pair and appends it to the table. But I need all the data from the arrays to be displayed in each column so that they look as if they correspond each other.
JS Function to create the main array:
//Generate array to hold predefined Stream Definitions
function PredefinedStreams() {
var StreamArray = new Array(3);
for (var q = 0; q < 3; q++)
{
StreamArray[q] = new Array(4);
for (var w=1; w<3; w++)
{
StreamArray[q][w] = new Array(5);
}
}
StreamArray[0][0]="Stream1";
StreamArray[0][1][0]="1_attr1";
StreamArray[0][1][1]="1_attr2";
StreamArray[0][1][2]="1_attr3";
StreamArray[0][1][3]="1_attr4";
StreamArray[0][1][4]="1_attr5";
StreamArray[0][2][0]="1_type1";
StreamArray[0][2][1]="1_type2";
StreamArray[0][2][2]="1_type3";
StreamArray[0][2][3]="1_type4";
StreamArray[0][2][4]="1_type5";
StreamArray[0][3] = "define stream Stream1 (1_attr1 1_type1, 1_attr2 1_type2, 1_attr3 1_type3, 1_attr4 1_type4, 1_attr5 1_type5 );";
StreamArray[1][0]="Stream2";
StreamArray[1][1][0]="2_attr1";
StreamArray[1][1][1]="2_attr2";
StreamArray[1][1][2]="2_attr3";
StreamArray[1][1][3]="2_attr4";
StreamArray[1][1][4]="2_attr5";
StreamArray[1][2][0]="2_type1";
StreamArray[1][2][1]="2_type2";
StreamArray[1][2][2]="2_type3";
StreamArray[1][2][3]="2_type4";
StreamArray[1][2][4]="2_type5";
StreamArray[1][3] = "define stream Stream2 (2_attr1 2_type1, 2_attr2 2_type2, 2_attr3 2_type3, 2_attr4 2_type4, 2_attr5 2_type5 );";
StreamArray[2][0]="Stream3";
StreamArray[2][1][0]="3_attr1";
StreamArray[2][1][1]="3_attr2";
StreamArray[2][1][2]="3_attr3";
StreamArray[2][1][3]="3_attr4";
StreamArray[2][1][4]="3_attr5";
StreamArray[2][2][0]="3_type1";
StreamArray[2][2][1]="3_type2";
StreamArray[2][2][2]="3_type3";
StreamArray[2][2][3]="3_type4";
StreamArray[2][2][4]="3_type5";
StreamArray[2][3] = "define stream Stream3 (3_attr1 3_type1, 3_attr2 3_type2, 3_attr3 3_type3, 3_attr4 3_type4, 3_attr5 3_type5 );";
return StreamArray;
}
JS Function to retrieve individual stream data onto arrays:
var streams = '<select id="streamSelect" onchange="showStreamDef()">', streamtypes = PredefinedStreams();
var streamDef = streamtypes = PredefinedStreams();
var stream1_attr = streamtypes = PredefinedStreams();
var stream1_type = streamtypes = PredefinedStreams();
var stream2_attr = streamtypes = PredefinedStreams();
var stream2_type = streamtypes = PredefinedStreams();
var stream3_attr = streamtypes = PredefinedStreams();
var stream3_type = streamtypes = PredefinedStreams();
var PredefinedStreamComboDiv=document.createElement('div');
function createattr()
{
for (var q = 0; q < 3; q++)
{
streams += "<option value='"+streamtypes[q][0]+"'>"+streamtypes[q][0]+"</option>";
streamDef += streamtypes[q][3];
for (var w=0; w<3; w++)
{
for(var r=0; r<5;r++)
{
if(q==0 && w==1)
{
stream1_attr[r] = streamtypes[q][w][r];
}
if(q==0 && w==2)
{
stream1_type[r] = streamtypes[q][w][r];
}
if(q==1 && w==1)
{
stream2_attr[r]= streamtypes[q][w][r];
}
if(q==1 && w==2)
{
stream2_type [r]= streamtypes[q][w][r];
}
if(q==2 && w==1)
{
stream3_attr [r]= streamtypes[q][w][r];
}
if(q==2 && w==2)
{
stream3_type [r]= streamtypes[q][w][r];
}
}
}
}
streams += '</select>';
//streamDef += '</select>';
PredefinedStreamComboDiv.className="attr-combobox-style";
PredefinedStreamComboDiv.innerHTML= streams;
PredefinedStream.appendChild(PredefinedStreamComboDiv);
}
JS Function to create the table:
function showStreamDef()
{
alert("Displaying Stream Details");
var choice=document.getElementById("streamSelect");
var selectedStr = choice.options[choice.selectedIndex].text;
var myTableDiv = document.getElementById("streamDefDiv");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.border = '1';
table.appendChild(tableBody);
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Attribute"));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Type"));
tr.appendChild(td);
if(selectedStr=="Stream1")
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream1_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream1_type[d]));
tr.appendChild(td);
}
}
else if(selectedStr=="Stream2")
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream2_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream2_type[d]));
tr.appendChild(td);
}
}
else
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream3_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream3_type[d]));
tr.appendChild(td);
}
}
tableBody.appendChild(tr);
myTableDiv.appendChild(table);
document.getElementById('streamDefDiv').style.display = "block";
}
The issue was only with the function where I dynamically generate the table.
As shown in the question, I've appended the row(tr) to the tablebody only at the end. This causes only the last saved data pair row to be appended to the table. So in order to get each row to be appended: once each table data(td) is appended to a row( tr), that particular tr needs to be appended to the tablebody.
function showStreamDef()
{
var choice=document.getElementById("streamSelect");
var selectedStr = choice.options[choice.selectedIndex].text;
var myTableDiv = document.getElementById("streamDefDiv");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.border = '1';
table.appendChild(tableBody);
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Attribute"));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Type"));
tr.appendChild(td);
tableBody.appendChild(tr);
if(selectedStr=="Stream1")
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream1_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream1_type[d]));
tr.appendChild(td);
tableBody.appendChild(tr);
}
}
else if(selectedStr=="Stream2")
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream2_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream2_type[d]));
tr.appendChild(td);
tableBody.appendChild(tr);
}
}
else
{
for (var d = 0; d < stream1_attr.length; d++)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream3_attr[d]));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(stream3_type[d]));
tr.appendChild(td);
tableBody.appendChild(tr);
}
}
myTableDiv.appendChild(table);
document.getElementById('streamDefDiv').style.display = "block";
}

How to add onClick function to this code

I am trying to add an onclick function to this table. So when I click on the cell it will change color from red to blue.
Relevant code below:
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<ruudud.value; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<ruudud.value; j++){
var td = document.createElement('TD');
td.width='50';
td.height='50';
td.style.backgroundColor="red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
There is many ways to do this as the below :
1 - In for loop
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
//************************************************
td.setAttribute("onclick", "yourFun(this)");
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
2 - By Function :
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
setFunction();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function setFunction() {
var myTableDiv = document.getElementById("myDynamicTable");
var tds = myTableDiv.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
tds[i].setAttribute("onclick", "yourFun(this)");
}
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
3- Or You can use Event Delegation see this http://davidwalsh.name/event-delegate
You can do it by setting the onclick attribute for each td in your for loop which calls a corresponding function to handle a class change. The colors can be defined in your css for the two classes.
// for loop addition
td.setAttribute('class', 'bgRed');
// and
td.setAttribute('onclick', chgColor(this));
// or
td.onclick(function(this) {return function() {chgColor(this);};})(this);
// Function for changing td background class/color
function chgColor(td){
td.className == "bgRed" ? td.className = "bgBlue" : td.className = "bgRed";
}
You can directly add the event listener on the table, and in the callback you can check the event source and act accordingly. The event source would be a node so if you want to hold any specific data, you can keep attributes and read them on event.

Outputting a 3D array as a table

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/

Categories

Resources