Im having a problem with my input box not showing any values.
var renumber = 0;
function addItem() {
renumber++;
var html = "<tr";
html += "<td id='itemNum'>" + renumber + "</td>";
html += "<td><input name='itemName[]'></td>";
html += "<td><input name='itemDescription[]'></td>";
html += "<td><span class='currency'>$</span><input id='perHour' value='0' name='amountPerHour[]'></td>";
html += "<td><input id='lineHours' value='0' name='hours[]'></td>";
html += "<td><span class='currency'>$</span><input id='lineTotal' onblur='lineTotal(this);' value='0' name='lineTotal[]'></td>";
html += "<td><button type='button' id='remove_button' onclick='removeItem();'> X </button></td>";
html += "</tr>";
document.getElementById("addItems").insertRow().innerHTML = html;
}
function removeItem() {
document.getElementById("addItems").deleteRow(0);
renumber--;
var reorder = tblRow.rows;
for(var i = 0; i < reorder.length; i++) {
renumber[i];
renumber++;
}
document.getElementById("itemNum").innerHTML = renumber;
}
function lineTotal(elem) {
var mainRow = document.getElementById(elem);
var AmtPerHour = mainRow.getElementsByTagName('td').getElementById('perHour')[0].value;
var lnHrs = mainRow.getElementsByTagName('td').getElementById('lineHours')[0].value;
var total = mainRow.getElementsByTagName('td').getElementById('lineTotal')[0];
var myResult = AmtPerHour * lnHrs;
total.value = myResult;
}
<table>
<tr>
<th>#</th>
<th>Item Name</th>
<th>Item Description</th>
<th>Amount Per Hour</th>
<th>Total Hours</th>
<th>Line Total</th>
</tr>
<tbody id="addItems"></tbody>
</table>
<p>
<button type="button" onclick="addItem();">
Add Item
</button>
</p>
<p>
Amount Due: $0.00
<script type="text/javascript">
//add the amounts from all items.
//if none added then have it set to zero.
</script>
</p>
<p>
Due Date:
<script type="text/javascript">
//start it 2 weeks from actual date
</script>
</p>
<p>
<input id="invoice_submit" type="submit" name="submit">
</p>
my biggest concern is the values not appearing.
Second problem, but one I can live with:
For rows, row1, row2, row3. if I delete row2, I would like it to then be row1, row2.
Right now it is row1, row3. I am talking about the # table section.
any ideas?
Hi please find below working snippet solving your first and second problems.
I made a few fixes to your code.
your data was not showing because getElementById expects you to pass element ID as string but you were passing element to it so this document.getElementById(elem) wont work.
you were calculating line total when that field is getting blurred but you should calculate line total also when user makes changes to either amount per hour or total hours so I added onblur to those fields also.
your delete row was deleting the first row always no matter which row I am trying to delete (document.getElementById("addItems").deleteRow(0); will always delete the first row in table) so I added the row reference to that function and now it deletes the appropriate row.
I added a Due Amount Total method to your Javascript to calculate due amount every time table is updated(insert/delete row) and updates the label value Amount Due: $0.00
I added the logic to renumber all the rows whenever a row is deleted. (your second problem is no more so dont live with it :) ).
var renumber = 0;
// trigger everytime there is change in the table row to calculate the new due amount.
function calculateDueAmount() {
var tblRows = document.getElementById("addItems").getElementsByTagName('tr');
let total = 0;
for (var i = 0; i < tblRows.length; i++) {
let lineTotal = tblRows[i].getElementsByTagName('td')[5].getElementsByTagName('input')[0].value;
total += Number(lineTotal)
}
document.getElementById("amountDue").innerText = total.toFixed(2);
}
// no changes required in this
function addItem() {
renumber++;
var html = "<tr>";
html += "<td id='itemNum'>" + renumber + "</td>";
html += "<td><input name='itemName[]'></td>";
html += "<td><input name='itemDescription[]'></td>";
html += "<td><span class='currency'>$</span><input id='perHour' onblur='lineTotal(this);' value='0' name='amountPerHour[]'></td>";
html += "<td><input id='lineHours' onblur='lineTotal(this);' value='0' name='hours[]'></td>";
html += "<td><span class='currency'>$</span><input id='lineTotal' onblur='lineTotal(this);' value='0' name='lineTotal[]'></td>";
html += "<td><button type='button' id='remove_button' onclick='removeItem(this);'> X </button></td>";
html += "</tr>";
document.getElementById("addItems").insertRow().innerHTML = html;
}
// updated and sanitized the logic to delete the row
function removeItem(elem) {
let rowToDelete = elem.parentElement.parentElement;
let rowNumber = rowToDelete.getElementsByTagName('td')[0].innerText;
document.getElementById("addItems").deleteRow(rowNumber - 1);
let tblRows = document.getElementById('addItems').getElementsByTagName('tr');
let j = 0;
for (; j < tblRows.length; j++) {
tblRows[j].getElementsByTagName('td')[0].innerText = j + 1
}
calculateDueAmount(); // calculate due amount since row got deleted.
renumber = j;
}
function lineTotal(elem) {
var mainRow = elem.parentElement.parentElement;
var AmtPerHour = mainRow.getElementsByTagName('td')[3].getElementsByTagName('input')[0].value;
var lnHrs = mainRow.getElementsByTagName('td')[4].getElementsByTagName('input')[0].value;
var total = mainRow.getElementsByTagName('td')[5].getElementsByTagName('input')[0];
var myResult = Number(AmtPerHour) * Number(lnHrs);
total.value = myResult;
calculateDueAmount(); // calculate due amount since row got added
}
<table>
<tr>
<th>#</th>
<th>Item Name</th>
<th>Item Description</th>
<th>Amount Per Hour</th>
<th>Total Hours</th>
<th>Line Total</th>
</tr>
<tbody id="addItems"></tbody>
</table>
<p>
<button type="button" onclick="addItem();">
Add Item
</button>
</p>
<p>
Amount Due: $<span id="amountDue">0.00</span>
<script type="text/javascript">
//add the amounts from all items.
//if none added then have it set to zero.
</script>
</p>
<p>
Due Date:
<script type="text/javascript">
//start it 2 weeks from actual date
</script>
</p>
<p>
<input id="invoice_submit" type="submit" name="submit">
</p>
Related
How can I populate my table with an array of local storage data?
function savePlayer() {
let Player = {player,score};
localStorage.setItem("Player", JSON.stringify(Player));
let getPlayerScore = Player;
let text = document.getElementById("topScores");
for(let i = 0; i <Player.length; i++){
text += "<tr>";
text += "<td>" + getPlayerScore[i].player + "</td>";
text += "<td>" + getPlayerScore[i].score + "</td></tr>";
}
Here's the HTML:
<body>
<table id = "topScores">
<tr>
<th>Username</th>
<th>Score</th>
</tr>
</table>
</body>
What am I doing wrong?
The Player.toString() isn't what you think it is.
var player = "Mario";
var score = 1000;
var Player = {
player,
score
};
// Print Player
console.log(JSON.stringify(Player));
console.log(Player.toString());
You can't just add text to an element; you need to set it though
innerHTML. Sadly, however, you can't set it for each row, because the DOM will try to end the tr tag, so you need to set everything at the same time through a string.
I couldn't get localStorage to work in the snippet so I commented out the code without testing it.
Another solution would be to append the elements, and honestly, that's what I would prefer, but I didn't want to steer to far away from your original solution, and I didn't want fix the "feature" where the DOM is autocompleting tr tags.
function savePlayer() {
// This wasn't an array to begin with, so I fixed that.
let Player = [{"player": "player","score": 10}];
// It's usually preferred to refer to a public constant when accessing localStorage.
let localStorageKey = "player";
/* localStorage.setItem(localStorageKey, JSON.stringify(Player));
let getPlayerScore = JSON.parse(localStorage.getItem(localStorageKey));*/
let getPlayerScore = Player;
let text = document.getElementById("topScores");
var playerRow = "";
for(let i = 0; i < getPlayerScore.length; i++){
playerRow = "<tr>";
playerRow += "<td>" + getPlayerScore[i].player + "</td>";
playerRow += "<td>" + getPlayerScore[i].score + "</td></tr>";
}
text.innerHTML += playerRow;
}
<body onload="savePlayer()">
<table id="topScores">
<tr>
<th>Username</th>
<th>Score</th>
</tr>
</table>
</body>
I'm dynamically creating rows in a table with 3 columns: Item, Description & QTY. How do I increment an array with each dynamically created table row?
Here's the results I'm getting when submitting the form below containing two rows with the following values.
The first row values are: Item1, Description1, Qty1
and the second row values are: Item2, Description2, Qty2
1=Item1&1=Description1&1=QTY1&1=Item2&1=Description2&1=QTY2
I would like to return the following instead:
1=Item1&1=Description1&1=QTY1&2=Item2&2=Description2&2=QTY2
https://jsfiddle.net/rimshot609/zgdvxo83/4/
<form name="SiteForm" id="SiteForm" method="post" action="mailto:test#test.com">
<div class="line-item">
<fieldset>
<table id="textbox" border="0">
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<input type="itembutton" onclick="createTableRows()" value="Add Item" />
</fieldset>
</div>
<input type="submit" name="subform" value="Submit Form" />
<script>
function createTableRows() {
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = rowlen;
for (i = 0; i < 2; i++) {
arr = ['1']; //I need this number to increase by 1 with each table row created.
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
} else {
x.innerHTML = "<input type='textbox' placeholder='Item Number' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='Description' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='QTY' name='" + arr[i] + "' required='required'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
</script>
</form>
Without deletion, it's very simple. Just replace this line:
arr = ['1']; //I need this number to increase by 1 with each table row created.
With this:
arr = [row.id]; //I need this number to increase by 1 with each table row created.
row.id is always set to table.rows.length.
But when you introduce Deletion into the equation things get more complicated. Each time you delete a row you'll want to either change the value for the existing rows, or use another value that you increment differently.
The first solution feels quite elegant, but with the way this has been set up would be a little clunky to implement. The other would require something like:
let highestValue = 0;
function createTableRows() {
highestValue++;
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = highestValue;
The problem is that you'll have gaps. If you have rows 1, 2 and 3 then delete 2, the results will jump from 1 to 3.
I've created a form when the user inputs the number of rows of the table which corresponds to number of subjects.I want the user to insert data into this table's columns or to fill it.How can i make this because my table just stands there chillin' and i can't insert data into it.
This is my code. Please someone shows me how to insert data into the columns of this table instead of phrases"one" and "two" i've used for demonstration.This code doesn't have errors so works very well.
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td> one </td><td> two </td></tr>";
}
}
</script>
</body>
</html>
I changed your code to insert inputs instead of "one" and "two", with classes subject and points. To store this information you will have to grab each row of your table and pull out the value of those inputs, and store it in the database.
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += '<tr><td><input type="text" class="subject" /></td><td><input type="text" class="points"/></td></tr>';
}
}
You use HTML input elements to allow the user to enter data into a form.
http://www.w3schools.com/tags/tag_input.asp
Please add input elements when you are adding rows. Try this:
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td><input type='text' id= 'sub'> </td><td><input type='text' id='points'></td></tr>";
}
}
</script>
</body>
</html>
Cheers !
So as a beginner, I have no idea how to create a table using Javascript. I can make a table using a simple html file but not in Javascript.
The output should have 2 columns and 4 rows. I also need to use the prompt tag in order to insert data for the second column. Not to mention that I need to average the total number in the 2nd column.
I tried searching but I got mixed results and its confusing me.so please help me
this is the html file
<html>
<body>
<table border="1" style="width:30%">
<tr>
<td>Rose</td>
<td>40</td>
</tr>
<tr>
<td>Daisy</td>
<td>50</td>
</tr>
<tr>
<td>Orchids</td>
<td>60</td>
</tr>
<tr>
<td>Flowers</td>
<td>150</td>
</tr>
</table>
</body>
</html>
Try this - >
var Rose = prompt("Enter price for Rose?");
var Daisy = prompt("Enter price for Daisy?");
var Orchids = prompt("Enter price for Orchids?");
var flowers = Number(Rose) + Number(Daisy) + Number(Orchids);
var table = document.createElement("table");
createTable();
function createTable(){
createTrTds("Rose",Rose);
createTrTds("Daisy",Daisy);
createTrTds("Orchids",Orchids);
createTrTds("Total",flowers);
document.getElementById("table").appendChild(table);
}
function createTrTds(text,value){
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var txt1 = document.createTextNode(text);
var txt2 = document.createTextNode(value);
td1.appendChild(txt1);
td2.appendChild(txt2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
td
{
border: 1px solid black;
}
<div id="table">
</div>
You will be helped by using a framework for this, jquery or angularjs comes to mind to solve it. However the pure JavaScript way looks like this:
This will create a table with inputs for the number of flowers and sum them up at the bottom when numbers change, you can also add more flower types in the JavaScript file.
var tabledef = [];
tabledef['Rose'] = 40;
tabledef['Daisy'] = 50;
tabledef['Orchids'] = 60;
writeTable();
function writeTable() {
var table = '<table border="1" style="width:30%">';
var sum = 0;
for (var i in tabledef) {
sum = sum + tabledef[i];
table = table + '<tr><td>' + i + '</td><td><input id="' + i + '" onchange="recalculate(this)" type="number" value="' + tabledef[i] + '"></td></tr>';
}
table = table + '<tr><td>Flowers</td><td>' + sum + '</td></tr></table>';
document.getElementById('myTable').innerHTML = table;
}
function recalculate(box) {
tabledef[box.id] = box.valueAsNumber;
writeTable();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myTable"></div>
<script src="createTable.js"></script>
</body>
</html>
You just need array with data and then fill table as thought it was an html document
var table = '<table border="1">',
data = [['Rose','Daisy','Orchids','Flowers'],[40,50,60,150]];
for (var i = 0; i < data[0].length; i++) {
table += '<tr>';
for (var j = 0; j < data.length; j++) {
table += '<td>' + data[j][i] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('container').innerHTML = table;
http://jsfiddle.net/5pdac6sb/
I've created dynamic table using HTML and javascript but rather than applying alternate color, I want to apply distinct color to each row. How can I do so?
<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<table>
<tr>
<td>Enter Rows</td>
<td><input type="number" id="txtRows"/></td>
</tr>
<tr>
<td>Enter Columns</td>
<td><input type="number" id="txtCols"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" id="btnDisplay" value="Display" onClick="createTable();"/></td>
</tr>
</table>
<table id="tbl_DynamicTable" border="1">
</table>
</body>
<script type="text/javascript">
function createTable()
{
debugger;
var rows = document.getElementById("txtRows").value;
var cols = document.getElementById("txtCols").value;
var table = document.getElementById("tbl_DynamicTable");
var str="";
for(var i=0;i<rows;i++)
{
str += "<tr id=row" + i +">";
//r = document.getElementById('tbl_DynamicTable').getElementsByTagName('<tr>');
//r.bgColor = colours[(i%k)/group | 0];
//mycurrent_row.style.backgroundColor = "#EEF4EA";
//mycurrent_row.style.backgroundColor =colours[(i%k)/group | 0];
for(var j=0;j<cols;j++)
{
if(i==0)
{
str += "<th> Header " + j + "</th>";
}
else
{
str += "<td> Row " + i + ", Cell "+ j + "</td>";
}
}
str += "</tr>";
}
table.innerHTML = str;
}
$("tr").style("bgcolor","red");
</script>
</html>
I don't know how to use jQuery with HTML page. I'm new to this. So if possible please let me know what is needed to include in this too.
You have many way to create a random color.
Use these example :
JAVASCRIPT
'#'+Math.floor(Math.random()*16777215).toString(16);
jQuery
(function(m,s,c){return (c ? arguments.callee(m,s,c-1) : '#') +
s[m.floor(m.random() * s.length)]})(Math,'0123456789ABCDEF',5)
And add this hexa random color on your TR when you generate it
HTML
<table border="1">
<tr bgcolor="#FF0000">
^ Here
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
Other example on http://www.paulirish.com/2009/random-hex-color-code-snippets/
javascript approach (i suggest including jQuery):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
// paint rows on document ready
$(function(){
paint_rows();
});
function paint_rows() {
$('#table_id tr').each(function(){
$(this).css('color', get_random_color());
});
}
</script>
just make sure to add enough color values into the array colors (can use hex values as well).
and, you can call the function paint_rows() whenever needed of course.
hope that helps.