Execute actions on a html element added with javascript - javascript

I am adding an element to an html page using javascript when a button is clicked and making an onclick attribute on this button to alert something as a test to make it execute something but it is not alerting anything when this added button is clicked. Here is the codes.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" id="inptext" type="text" placeholder="Your email..."></input>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td>' + x + '</td><td>' + y + '</td></tr>';
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + '<button onclick="myFunctionedit()" style="margin-left:8px" class="edit" id="vda' + z + '">Edit</button><button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button><button style="margin-left:8px" class="update" id="cvda' + z + '">Update</button></div><div id="zzza' + z + '" style="height:10px"></div>';
document.getElementById('cvda'+z).style.visibility = 'hidden';
z = z+1;
}
</script>
</body>
</html>

Inside the alert you are using double quotes:
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">
Try changing it to single quotes:
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">

<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
makes for invalid html.
Try
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
On top of that, the float: right; in #buttons is making the buttons unclickable. You can either remove that float or give it a z-index.
Working JSFiddle: https://jsfiddle.net/L8ymqLwh/ (with float: right; removed)

Related

how to add css to table consistently

I made this simple website that adds and removes rows from a table. I have a two problems.The first one is whenever i add elements and them start deleting them my css style for my table is gone. Any idea how to fix it ? For example if i add 5rows and try to delete two of them then my style for all rows is gone. The second problem is how can i implement a function counter that will change the number of elements in the table and will keep track of them whenever someone removes or add new element. Here is my code:
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable() {
var radio = document.getElementsByName("content");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected =
radio[a].value;
}
}
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + radio_selected + "</td>" +
"<td>" + "<input type='button' onclick='post(this);' id='post' value='Post'>" +
"<input type='button' onclick='remove(this);' id='remove'value='Remove'>" + "</td>" + "</tr>"
}
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML += 1;
}
function remove(btn) {
var row = btn.parentNode.parentNode;
var removed = document.getElementById("removed");
row.parentNode.removeChild(row);
}
function post(btn) {
var row = btn.parentNode;
row.parentNode.style.backgroundColor = "Green";
btn.setAttribute("disabled", "true");
btn.parentNode.lastElementChild.setAttribute("disabled", "true");
}
label {
width: 100px;
display: inline-block;
}
table,
th,
td,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
}
table td {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<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">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
<div>
<label for="content" id="contentlabel">Content type</label>
<input type="radio" name="content" value="Free" class="content">Free
<input type="radio" name="content" value="Paid" class="content">Paid
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable(); counter();">
</div>
<div>
<h1>Number of elements<span id="counterForElements">0</span></h1>
</div>
<div>
<table id="output">
<th style="width:40%;">Title</th>
<th style="width:40%;">Author</th>
<th style="width:10%;">Type</th>
<th style="width:10%;">Button</th>
</table>
</div>
<div>
<h1>Removed elements</h1>
<table id="removed">
</table>
</div>
</body>
</html>
I think I have found what cause the border issue in Firefox.
Your output is set to the <table>, but you used <th> without <thead> nor <th>.
I simply added those missing tags, then I set the output to a new <tbody> tag.
It seems to work fine now.
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable() {
var radio = document.getElementsByName("content");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected =
radio[a].value;
}
}
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + radio_selected + "</td>" +
"<td>" + "<input type='button' onclick='post(this);' id='post' value='Post'>" +
"<input type='button' onclick='remove(this);' id='remove'value='Remove'>" + "</td>" + "</tr>"
}
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML += 1;
}
function remove(btn) {
var row = btn.parentNode.parentNode;
var removed = document.getElementById("removed");
row.parentNode.removeChild(row);
}
function post(btn) {
var row = btn.parentNode;
row.parentNode.style.backgroundColor = "Green";
btn.setAttribute("disabled", "true");
btn.parentNode.lastElementChild.setAttribute("disabled", "true");
}
label {
width: 100px;
display: inline-block;
}
table,
th,
td,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
}
table td {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<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">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
<div>
<label for="content" id="contentlabel">Content type</label>
<input type="radio" name="content" value="Free" class="content">Free
<input type="radio" name="content" value="Paid" class="content">Paid
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable(); counter();">
</div>
<div>
<h1>Number of elements<span id="counterForElements">0</span></h1>
</div>
<div>
<table>
<thead>
<th style="width:40%;">Title</th>
<th style="width:40%;">Author</th>
<th style="width:10%;">Type</th>
<th style="width:10%;">Button</th>
</thead>
<tbody id="output">
</tbody>
</table>
</div>
<div>
<h1>Removed elements</h1>
<table id="removed">
</table>
</div>
</body>
</html>
Your counter() function is not properly treating the innerHTML property as an integer. Here is a fix:
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
Another way would be with a global variable:
let counter = 0;
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML = ++counter;
}
If you want to keep track of removals, you would need to do so in remove():
function remove(btn) {
// ... existing code goes here
counter.innerHTML = parseInt(counter.innerHTML) + 1;
// or:
counter.innerHTML = --counter;
}
Another way would be to count the number of <tr> elements in the table and store that in counter.innerHTML every time you add or remove a row.

Can't calculate the sum of table rows I've tried many ways from the internet but nothing

I want to build tables that fetch data from api and I succeeded in that so I need now to calculate numbers of table rows and show total in next row or in span div it does not matter. I just need total as shown in image..
I already tried many solutions to calculate rows but always get result zero or NaN. I'm not sure what I'm doing wrong or maybe I just made mistake somewhere in this code... I would appreciate your opinion or solution if possible.
function statsYesterday() {
$.getJSON('https://api.url, function(data) {
var data, i, offer, creative, id, conversion, clicks, payout = "";
for (i in data.response.data.data) {
offer += "<table><tr><td>" + data.response.data.data[i].Offer.name + "</td></tr></table>";
creative += "<table><tr><td>" + data.response.data.data[i].OfferUrl.name + "</td></tr></table>";
id += "<table><tr><td>" + data.response.data.data[i].Stat.affiliate_info1 + "</td></tr></table>";
conversion += "<table><tr><td>" + data.response.data.data[i].Stat.conversions + "</td></tr></table>";
clicks += "<table><tr><td>" + data.response.data.data[i].Stat.clicks + "</td></tr></table>";
//this code reduce payout by 20%
var num = parseFloat(data.response.data.data[i].Stat.payout);
var val = num - (num * .20);
payout += "<table><tr><td> € " + val + "</td></tr></table>";
});
//end reduce code
//this is how code look like without reducing percentage
//payout += "<table><tr><td>" + data.response.data.data[i].Stat.payout + "</td></tr></table>";
document.getElementById("offer_name").innerHTML = offer;
document.getElementById("creative_name").innerHTML = creative;
document.getElementById("id_name").innerHTML = id;
document.getElementById("converion_name").innerHTML = conversion;
document.getElementById("clicks_name").innerHTML = clicks;
document.getElementById("payout_name").innerHTML = payout;
};
});
};
<body>
<div class="container">
<br><br><button onclick="statsYesterday()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Yesterday</button> <button onclick="statsToday()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Today</button> <button onclick="statsLastWeek()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Last Week</button>
<br><br>
<table class="table" id="table">
<thead>
<tr>
<th>Offer</th>
<th>Creative</th>
<th>SubID</th>
<th>Conversion</th>
<th>Clicks</th>
<th>Payout</th>
</tr>
</thead>
<tbody>
<tr>
<td id="offer_name"></td>
<td id="creative_name"></td>
<td id="id_name"></td>
<td id="converion_name"></td>
<td id="clicks_name"></td>
<td id="payout_name" style="padding-top:30px;"></td>
</tr>
</tbody>
</table>
<br><br>
</div>
</body>
push the values into an array and then you can perform an addition on them later
something like this
values=[]
//... your code
var num = parseFloat(data.response.data.data[i].Stat.payout);
var val = num - (num * .20);
values.push(val)
and then later you can simply iterate over the array and add the values
let total=values.reduce((acc,curr)=>acc+curr)
document.getElementById("total").textContent=total

stop onclick javascript function from repeating my rows in table

I have a button -
<a onclick="function edit_row()"></a>
When I click the button it invokes the function edit_row and opens a new row in a table which I can edit.
The problem is that every time I click the button, it opens a new row. I want to stop that. I want it to just open one row which holds the row id.
Script code:
function edit_row(process_id, row_id, item_id, quantity, price, total) {
$(".edit_row").remove();
$(".add_row").remove();
var row = '<tr class="bg-success"> <
td > <?php echo $lang['e_edit_items'];?>: < /td> <
td > '+ item_id +' < /td>';
row += '<td><?php echo $lang['
quantity '];?></td>';
row += '<td><input type="text" class="form-control" id="quant1" value="' + quantity + '"></td><td><?php echo $lang['
The - price '];?></td>';
row += '<td><input type="text" id="price1" class="form-control" value="' + price + '"></td>';
row += '<td><a class="btn btn-success btn-block"onclick="save_edit(' + process_id + ',' + row_id + ',' + item_id + ',' + quantity + ',' + total + ')"><?php echo $lang['
Save_edit '];?></a></td></tr>';
$("#" + row_id).after(row);
return false;
}
You can remove click event handler of clickable element like this example.
$("#button1").click(function(){
$("table").append("<tr><td>New-1</td><td>New-2</td><td>New-3</td></tr>");
$(this).unbind("click");
});
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add row
<table>
<tr>
<td>Column-1</td>
<td>Column-2</td>
<td>Column-3</td>
</tr>
<tr>
<td>Column-1</td>
<td>Column-2</td>
<td>Column-3</td>
</tr>
</table>
But there is many way to do this work. For example you can add disabled attribute to clickable element, if it is button, You can add data-* attribute or class to element or use variable to do this. See example of other way in jsfiddle

Show/Hide Not Working When Fields Added Using .after () Function [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
When I add fields using the jQuery .after() function, the show/hide functionality does not work on those fields.
Here's a JSFiddle that demonstrates the issue:
JSFiddle Demo
The show/hide functionality works on the first row, but does not work on any rows added after that one. I think the code being written after the page has been loaded might be the issue, but I'm not certain. If that's the case, is there a work around other than hard coding a certain amount of rows?
Here's the code I'm working with:
CSS:
#Table {
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse:collapse;
}
#Table td, #Table th {
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#Table th {
font-size:1.4em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#fff;
}
#Table tr.alt td {
color:#000;
background-color:#EAF2D3;
}
HTML:
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />
jQuery:
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function () {
$('.cause_details').hide();
$('.report_cause').change(function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function () {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});
This:
$('.report_cause').change(function () {
Only applies to the .report_cause elements that existed when it was called. To handle new elements, you need a delegated handler:
$(document).on('change', '.report_cause', function(){
Additionally, if you want the new elements initially hidden, modify your output HTML accordingly:
'<p class=\"cause_details\" style=\"display:none\">'+
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function() {
$('.cause_details').hide();
$(document).on('change', '.report_cause', function() {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function() {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\" style=\"display:none\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});
#Table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
}
#Table td,
#Table th {
font-size: 1em;
border: 1px solid #98bf21;
padding: 3px 7px 2px 7px;
}
#Table th {
font-size: 1.4em;
text-align: left;
padding-top: 5px;
padding-bottom: 4px;
background-color: #A7C942;
color: #fff;
}
#Table tr.alt td {
color: #000;
background-color: #EAF2D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />
Try this. The problem is that when you create a dynamic element, you need to again register change event on $('.report_cause').
$(document).ready(function(){
$('.cause_details').hide();
BindChange();
$('#btnAdd').click(function(){
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>'+table_count2+'</td>'+
'<td>'+
'<select name=\"report_cause'+count_2+'\" id=\"report_cause'+count_2+'\" class=\"report_cause\">'+
'<option value=\'default\'>-</option>'+
'<option value=\'other\'>Other, Not Listed</option>'+
'</select>'+
'<p class=\"cause_details\">'+
'<input type=\"text\" name=\"cause_detail_info'+count_2+'\" id=\"cause_detail_info'+count_2+'\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />'+
'</p>'+
'</td></tr>');
BindChange();
});
});
function BindChange()
{
$('.report_cause').bind("change",function(){
if ($(this).val() == 'other'){
$(this).parent().find('.cause_details').show();
}else{
$(this).parent().find('.cause_details').hide();
}
});
}
https://jsfiddle.net/hnj6ed1y/12/
When you create the elements dynamically, you need to use event delegation to handle the events on them, so based on your jQuery version use .bind or .on API.
Just change in your code to:
$(document).on('change', '.report_cause', function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});

Create HTML table using Javascript

My question will ultimately be related to this site:
http://dbtest.net16.net/ethanol-01.html
EDIT: View unencrypted page source code here >>> http://dbtest.net16.net/ethanol-22.html
This is an HTML form with results calculated using JavaScript. My goal is to display a table of 2-6 columns and variable number of rows depending on user input (form would be modified). My problem is that I am not fully understanding how to get the table created in JavaScript after the user clicks the Calculate button. I have found some potential good answers but apparently don't fully understand it all. Running the following code is somewhat like what I want my output to display.
<html>
<!-- http://www.java2s.com/Tutorial/JavaScript/0220__Array/OutputarrayelementinaHTMLtableformat.htm -->
<head>
<title>Table of Numbers</title>
</head>
<body>
<h1>Table of Numbers</h1>
<table border="0">
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
document.write("<tr><td style='width: 100px; color: red;'>Col Head 1</td>");
document.write("<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>");
document.write("<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>");
document.write("<tr><td style='width: 100px;'>---------------</td>");
document.write("<td style='width: 100px; text-align: right;'>---------------</td>");
document.write("<td style='width: 100px; text-align: right;'>---------------</td></tr>");
for (var i = 0; i < 8; i++) {
document.write("<tr><td style='width: 100px;'>Number " + i + " is:</td>");
myArray[i] = myArray[i].toFixed(3);
document.write("<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>");
document.write("<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>");
}
//-->
</script>
</table>
</body>
</html>
If I can get the test table to be created and populated with my test data using my actual javascript file, then I should then be able to figure the rest myself (I think).
Following are a couple of the best answers I could find so far:
http://jsfiddle.net/drewnoakes/YAXDZ/
The above link originated in stackoverflow but I can't seem to find the original post at this time.
http://www.java2s.com/Tutorial/JavaScript/0220__Array/OutputarrayelementinaHTMLtableformat.htm
Any help is appreciated. Simpler is better due to my limited experience.
The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable) use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
In the html file there are three input boxes with userid,username,department respectively.
These inputboxes are used to get the input from the user.
The user can add any number of inputs to the page.
When clicking the button the script will enable the debugger mode.
In javascript, to enable the debugger mode, we have to add the following tag in the javascript.
/************************************************************************\
Tools->Internet Options-->Advanced-->uncheck
Disable script debugging(Internet Explorer)
Disable script debugging(Other)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Table</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
function CmdAdd_onclick() {
var newTable,startTag,endTag;
//Creating a new table
startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
<TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"
endTag="</TBODY></TABLE>"
newTable=startTag;
var trContents;
//Get the row contents
trContents=document.body.getElementsByTagName('TR');
if(trContents.length>1)
{
for(i=1;i<trContents.length;i++)
{
if(trContents(i).innerHTML)
{
// Add previous rows
newTable+="<TR>";
newTable+=trContents(i).innerHTML;
newTable+="</TR>";
}
}
}
//Add the Latest row
newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
document.getElementById('userid').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('username').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('department').value +"</TD><TR>";
newTable+=endTag;
//Update the Previous Table With New Table.
document.getElementById('tableDiv').innerHTML=newTable;
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<label>UserID</label>
<input id="userid" type="text" /><br />
<label>UserName</label>
<input id="username" type="text" /><br />
<label>Department</label>
<input id="department" type="text" />
<center>
<input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
</center>
</div>
<div id="tableDiv" style="text-align:center" >
<table id="mainTable">
<tr style="width:120px " >
<td >User ID</td>
<td>User Name</td>
<td>Department</td>
</tr>
</table>
</div>
</form>
</body>
</html>
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}

Categories

Resources