Add event listener to each td - javascript

Here, I'm generating table by creating td's and tr's by clicking buttons, how can I add event listener to every td, and when it's clicked I can know the tr where this td placed.
var table = document.createElement('table');
document.body.appendChild(table);
var tr = document.createElement('tr');
table.appendChild(tr);
var td = document.createElement('td');
tr.appendChild(td);
var createTd = document.createElement('button');
createTd.innerHTML = 'Create td';
document.body.appendChild(createTd);
var createTr = document.createElement('button');
createTr.innerHTML = 'Create tr';
document.body.appendChild(createTr);
createTd.addEventListener('click',function() {
td = document.createElement('td');
tr.appendChild(td);
})
createTr.addEventListener('click',function() {
tr = document.createElement('tr');
table.appendChild(tr);
})

You can add it
var createTd = document.createElement('button');
createTd.innerHTML = 'Create td';
createTd.onclick = function() {
// to do something
};
document.body.appendChild(createTd);
var createTr = document.createElement('button');
createTr.innerHTML = 'Create tr';
createTr.onclick = function() {
// to do something
};
document.body.appendChild(createTr);

Related

How to get values of a full <tr> tag in javascript after on change?

I have created a table inside javascript, with 3 input tags
item_name,
item_value and
quantity.
On change quantity input tag, i want to get the values of all 3 input tags in that particular row to calculate the quantity. How to get the full data of <tr> ?
This is my table,
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = entry[0];
let value = entry[1];
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
tr.appendChild(td);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
//$('#receipt_details').append(quantity);
td.appendChild(quantity);
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
$('#receipt_details').append(table);
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
You can try using input event like the following way:
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = 'some key';
let value = {amount:'100'};
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
tr.appendChild(td);
td.appendChild(quantity);
tr.appendChild(td);
const tbody = document.createElement("tbody");
tbody.appendChild(tr);
const table = document.createElement("table");
table.appendChild(tbody);
$('#receipt_details').append(table);
$('table input').on('input', function(){
var parent = $(this).closest('tr');
var value = parent.find('[name="item_value[]"]').val();
var amount = parent.find('[name="quantity[]"]').val();
var total_cost = value * amount;
parent.find('[name="total_cost[]"]').val(total_cost);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
var value = $('tr').text();
if you can give id or class to the tr then it will be like e.g ( ) then it will be like
var value = $('#tablerow').text();
you can get it like this fiddle
quantity.onchange = function(e) {
var row = {};
$(e.target).closest('tr').find("input:text").each(function() {
row[$(this).attr("name")] = $(this).val();
});
console.log(row);
}

Get selected row value using javascript

I have dynamically add the table on html button click. Add the teamname,teamid,radio button.
HTML attributes:
<input type="button" value="Generate a table." onclick="generate_table()">
Javascript function :
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
4 rows with 3 columns will generate on the button click , Now i need to get the details on the radio button click.
If i select the radio button from the first row i need to show the teamid in alert box? how can I achieve this in javascript?
try this code below should alert teamid cell's innerText
<input type="button" value="Generate a table." onclick="generate_table()">
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
//here we set value of radio button based on element index and we set a classname for teamid cell
radio.setAttribute("value", i);
cell1.setAttribute("class", "selected_teamid");
//here we add click event
radio.setAttribute("onclick", "getteamid("+i+")");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
function getteamid(i){
alert(document.getElementsByClassName("selected_teamid")[i].innerText);
}
<input type="button" value="Generate a table." onclick="generate_table()">
just add this line, before appending the radio element:
radio.onclick = function(){alert(this.value};
You just need to add an event handler to the radio button when you create it:
...
radio.addEventListener('click', radioButtonClick, false);
...
function radioButtonClick() {
alert(this.getAttribute('value'));
}
This requires that you set the value of the radio button to your team id, or store it on the radio button (which will be the this inside the event handler) in some other way.
You aren't passing a teamid anywhere, so I assumed the teamid is the index of the looped array.
var generate_table = function()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
radio.setAttribute('data-team', i); // passing the team id
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
// add an event listener on a dynamic element, and alert the team id
document.addEventListener('click', function(e) {
if(e.target && e.target.hasAttribute('data-team')) {
alert(e.target.getAttribute('data-team'));
}
});
You have several way to achieve that:
The easiest way I think is to add an attribute 'teamid' to the radio button. Then just listen for click event and get this value back.
radio.setAttribute('teamid', teamid);
radio.addEventListener('click', onRadioClick);
function onRadioClick(domEvent){
console.log(domEvent.target.getAttribute('teamid'));
}
For me it is not the best way because you need to put some information in the DOM... In my opinion, it would be better to separate the presentation and the data :
var tableData = [
{teamId: 'someId0', title:'title0', someData:'...' },
{teamId: 'someId1', title:'title1', someData:'...' },
{teamId: 'someId2', title:'title2', someData:'...' }
];
for (var i = 0, n = tableData.length ; i < n ; i++){
var rowData = tableData[i];
// Create the row using rowData
// ...
radio.setAttribute('teamid', rowData.teamId);
radio.addEventListener('click', onRadioClick.bind(rowData));
// ...
}
function onRadioClick(domEvent){
// Here this represent data of the row clicked
console.log(this.teamId);
}
I think it's easier to manage because every data are JS side... You don't store any data in the DOM... However both works ;) Hope it helps
radio.setAttribute("onclick", "anotherFunction(this)")
and after this function create anotherFunction():
function anotherFunction(object){
alert(object.parentNode.parentNode.firstChild.innerHTML);
}

Bootstrap Table not appearing correctly

I am using JavaScript to loop through some data and build a number of tables and am using Bootstrap with the class table table-hover. This works absolutely fine on all tables except the very last table to be produced. The bottom table is always sqashed and the hover over doesn't work. The columns resize to the correct size but that's about it.
I can't work it out, both tables have the class declared:
No matter how many tables are made it always happens on the very last table. I should point out that I've tried everything I can think of including adding a dummy table within the loop and the last interation but then that makes two squashed tables then.
Update: http://jsfiddle.net/si828/1ksyces5/8/
Code:
$('#tableContainer').empty();
var div = document.getElementById('tableContainer');
for (var i = 0; i < data.length; i++)
{
div.innerHTML = div.innerHTML;
var para = document.createElement("p");
var logo = document.createElement("a");
logo.setAttribute('class', 'glyphicon glyphicon-user');
para.appendChild(logo);
var node = document.createTextNode(" " + data[i].userName + " (" + data[i].userID + ") " );
para.appendChild(node);
var aTag = document.createElement("a");
aTag.setAttribute('data-id-proxy' , data[i].userID);
aTag.setAttribute('class' , 'open-AddUserModal');
aTag.setAttribute('href' ,'#addUserModal');
var span = document.createElement("span");
span.setAttribute('class', 'glyphicon glyphicon-plus');
aTag.appendChild(span);
para.appendChild(node);
para.appendChild(aTag);
para.setAttribute('class', 'text-primary');
div.appendChild(para);
var table = document.createElement('table'), tr, td, row, cell;
table.setAttribute('class', 'table table-hover');
table.setAttribute('id', 'table' + data[i].userID);
table.setAttribute('border', '1');
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "SRM";
var cell = row.insertCell(1);
cell.setAttribute('style' , 'width: 13%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User";
var cell = row.insertCell(2);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User Name";
for (row = 0; row < data[i].targetUsers.length; row++)
{
tr = document.createElement('tr');
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].srm;
table.appendChild(tr);
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUser;
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUserName;
}
document.getElementById('tableContainer').appendChild(table);
}
Based on your JSFiddle, your div.innerHTML = div.innerHTML; on line 10 should be the last statement of your outer for loop (on line 76). Otherwise your table doesn't get a <tbody>, causing bootstrap to malfunction.
Here is the fixed one: http://jsfiddle.net/wsLzk5wq/
If it is only the last table you could add custom css for the last table element by using a child selector.
E.g
HTML:
<div class="parent-container">
<table>
.......
</table>
</div>
CSS:
.parent-container table:last-child {
padding: 10px !important;
.......
}

How to delete the table row on button click

var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onclick = function(){ };
var table = document.getElementById("myTableData");
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD');
td.width='175';
td.appendChild(el);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(objLabel);
td.appendChild(objLabel2);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(el_s);
td.appendChild(el_sm);
td.appendChild(el_sy);
tr.appendChild(td);
**var td = document.createElement('TD');
td.width='20';
td.appendChild(del);
tr.appendChild(td);**
myTableData.appendChild(table);
In the above code I have created a table dynamically and added NAME field GENDER field and DATE OF BIRTH field and DELETE BUTTON.
The code works like this: first the user has to enter details in NAME GENDER AND DOB, if the DELETE button is clicked then the columns containing fields are deleted from the table.
I have to insert the code for deletion here:
del.onclick = function(){ };
Try this:
del.onclick = function(){
var tr = document.createElement('TR');
tr.parentElement.removeChild(tr);
};

onclick functionality for dynamically added button is not working

I have developed a mobile webpage using HTML5+JS. I added a button dynamically to webpage. But when i added onclick functionality to that button, it's not working.
My Html code is;
<head><script>
var myarray = ['a','b','c','d','e','f'];
var arr = document.getElementById('content');
for(i=0;i<myarray.length;i++)
{
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function(){
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
</script>
<style>
.table { width:100%;height:70px;}
.Btn { margin-top:3px;border-radius:0;font-size:15px;height:30px;width:100px; color:#FFFFFF; margin-left:auto;margin-right:auto;display:block; }
</style></head>
<body><section id='content'></section></body>
It's not the onclick that's the problem. The problem is you are trying to get the #content element before it is loaded/rendered.
The solution is to wrap the code in window.onload which ensures the code will only execute when the elements in the page are loaded and ready for use:
window.onload = function () {
var myarray = ['a', 'b', 'c', 'd', 'e', 'f'];
var arr = document.getElementById('content');
for (i = 0; i < myarray.length; i++) {
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function () {
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
};
The problem is your code is not running on dom ready
window.onload = function (){
var myarray = ['a','b','c','d','e','f'];
var arr = document.getElementById('content');
for(i=0;i<myarray.length;i++)
{
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function(){
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
}
Demo: Plunker

Categories