How to add onClick function to this code - javascript

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.

Related

Set type text inside cell 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>

js button generator with functions

I got the code to generate the table with buttons i wanted,
but i also want to get a "onlick="cell_id(" + j +"," + i ")" function within the <button> element using js.
The j and i variables are to mark the row and column where the click came from and also used to create the table.
the code:
function tableCreate() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var j = 0; j <= 10; j++) {
var row = document.createElement("tr");
for (var i = 0; i <10; i++) {
var cell = document.createElement("td");
var button = document.createElement("button");
button.innerHTML = j +"-"+i;
cell.appendChild(button);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function cell_id(x,y){
window.alert('x:'+x+ ' y:'+y)
}
code from https://stackoverflow.com/a/61549235/12825970
You can attach a listener to each button element:
function tableCreate() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var j = 0; j <= 10; j++) {
var row = document.createElement("tr");
for (var i = 0; i <10; i++) {
var cell = document.createElement("td");
var button = document.createElement("button");
button.innerHTML = j +"-"+i;
setupListener(button);
cell.appendChild(button);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function setupListener(button, i, j) {
button.addEventListener('click', () => {
cell_id(button, i, j);
});
}
function cell_id(button, x, y){
msg('x:'+x+ ' y:'+y)
}
This approach works, but is expensive if you have a lot of buttons. For a more advanced approach, you can store the i and j as data attributes on the button, then use a single click event on the entire table. You can filter the events to check if they came from a "source" button. I'll leave that up to you if it's an option you want to pursue.

How to move cell data values from one column to another in HTML table with Javascript?

I want to rotate the values in HTML table rows with button, but in the following code "Move" button is not working. Display button will give following table:
0 1 2
0 1 2
0 1 2
by clicking on move button I want table as follows:
2 0 1
2 0 1
2 0 1
and keep rotating the values in row by clicking the move button
<body>
<script>
var myArray = new Array();
var i=0;
var j=0;
function display()
{
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (i = 0; i < 4; i++){
var tr = document.createElement('tr');
for (j = 0; j < 4; j++)
{
var td= document.createElement('td');
var text = document.createTextNode(j);
td.appendChild(text);
tr.appendChild(td);
table.appendChild(tr);
document.body.appendChild(table);
}
}
}
function move()
{
var table = document.getElementById('tbl');
for(i=0;i<4;i++)
{
var x = table.rows[i].cells[9].innerHTML;
for(j=0;j<4;j++)
{
table.rows[i].cells[j+1].innerHTML = table.rows[i].cells[j].innerHTML;
}
table.rows[i].cells[0].innerHTML=x;
}
}
</script>
HTML:
<input id="display" type="button" value="Display" onclick="display();" />
<input id="move" type="button" value="Move" onclick="move();" />
maybe:
function display() {
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (var i = 0; i < 4; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 4; j++) {
var td = document.createElement('td');
var text = document.createTextNode(j);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
function move() {
var table = document.querySelector('#tbl');
var tr = table.rows;
for (var i = 0; i < tr.length; i++) {
tr[i].insertBefore(tr[i].lastElementChild, tr[i].firstElementChild);
}
}

how to add data in a dynamic table

hi i have a table which is created dynamically .this is the code for table creation
function table() {
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
id = 0;
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
}
}
$(".lefttablediv").append(tbl);
};
table();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
now it is empty table i want add different data in each tr how can i add data?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Html>
<body id ="body">
</body>
</html>
<script>
function table() {
var body = document.body;
var tbl = document.createElement('table');
var tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
alert(tbl);
console.log(tbl);
id=0
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode("Please add some text here"));
}
}
$("#body").append(tbl);
};
table();
</script>
td.appendChild(document.createTextNode("")); you are appending blank data which showing blank page add some text it will reflect on page
***** td.appendChild(document.createTextNode("Please add sone text here"))****

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";
}

Categories

Resources