Adding data into a table and saving it into a database - javascript

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 !

Related

How to loop through an array and display user input with indexes?

How do i loop through an array and display user input with indexes without the user input replicating?
Current output i'm getting:
Feedback 1
123456
Feedback 2
123456
The expected output for the case below should be:
Feedback 1
123
Feedback 2
456
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Feedback Form</h2><br>
<form>
Enter Feedback : <textarea rows="3" cols="20" id="feedback"></textarea><br><br>
<input type="button" value="Submit Feedback" id="create" onclick="addFeedback()"><br><br>
<input type="button" value="View Feedback" id="view" onclick="displayFeedback()"><br><br>
</form>
<div id="result"></div>
</body>
</html>
var myArray = [];
var myFeedback = document.getElementById("feedback");
var displayBox = document.getElementById("result");
function addFeedback(){
//Store feedback into array
myArray.push(myFeedback.value);
//Clear textbox
myFeedback.value = "";
//Display message
displayBox.innerHTML = "Successfully Added Feedback Details!";
}
function displayFeedback(){
displayBox.innerHTML = "";
for(var i = 0; i < myArray.length; i++){
displayBox.innerHTML += "Feedback " + (i+1) + "<br/>" + myArray.join();
}
}
Use myArray[i] instead of join. Or more modern approach:
let innerHTML = "<ul>";
myArray.forEach((value, index) => {
innerHTML += `<li>Feedback ${index+1}: <br /> ${value}</li>`;
});
innerHTML += "</ul>";
displayBox.innerHTML = innerHTML;

get calculation on dynamic add row in javascript

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>

Creating div tag dynamically based on rows count

I have a database table which has rows. Based on the table rows, I want to create div tags dynamically. My requirement is like I have to create divs based on the database rows count.
If 5 rows are there in the db, then 1 div will be created.
If 20 rows are there in the db, then 2 divs will be created.
If 25 rows are there in the db, then 3 divs will be created.
If 56 rows are there in the db, then 6 divs will be created.
The 1st div should be beside the 2nd div.
Below is the javascript function I'm using:
function LoadData(data)
{
var rows_count = 22; -- will be fetched from DB side
var rowNum = Math.ceil(parseFloat(rows_count));
var resultHtml = '';
resultHtml += "<table style = \'width:100%;\' border=\'0\' colspan=\'2\' id=\'tbl_user\'>";
for (var i = 0; i <=rowNum-1 ; i++) {
resultHtml += '<tr>';
resultHtml += '<td border = 1><input type="name" placeholder="text goes here..."></td>';
resultHtml += '</tr>';
}
}
resultHtml += '</table>';
}
I have written out the logic, but 22 rows are creating only one div tag.
I want to show 10 records in 1 div and another 10 records in the 2nd div and so on.
Your Solution
$('#rows').change(function(e) {
var rows_count = parseInt($(this).val());
var div_count = Math.ceil(rows_count/10);
resultHtml = '<table width="100%" border="1px"><tr>';
j=0;l=0;
for (var i = 1; i<=div_count ; i++){k=0;
if(l==4){ resultHtml += '</tr><tr>';l=0;}
resultHtml += '<td align="center">';
while((j<rows_count)&&(k<10)){ resultHtml += '<input type="name" placeholder="text goes here..."><br>';j++;k++;}
resultHtml += '</td>';
l++;
}
resultHtml += '</tr></table>';
$('#inputs').html(resultHtml);
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>.active {
background: red;
color:#FFF;
}</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs"></div>
<input type="text" id="rows" placeholder="No. of Rows" />

How to convert HTML table to Javascript

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/

Print a table inside a div with given row and column via Javascript

I have two textfield and one button. When user clicked the button, It calls a function and print a table inside a div with given number of rows and columns.
You can see my code below, but this is not working as expected.
HTML
Rows <input type="text" id="rows">
Columns <input type="text" id="columns">
<input type="button" value="Create Table" onClick="printTable();">
<div id="box"></div>
Javascript
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
spaceofDiv.innerHTML=("<table border=1>");
for(i=0; i<nRows.value; i++)
{
spaceofDiv.innerHTML=("<tr>");
for(j=0; j<nColumns.value; j++)
{
spaceofDiv.innerHTML=("<td width=50 height=50> ");
}
}
spaceofDiv.innerHTML=("</table>");
}
You need to remember to
A) Close your table row and table cell elements
B) Concatenate the value of the table markup, as you are currently overwriting your changes with each assignment
var markup = '';
markup = "<table border=1>";
for(i=0; i<nRows.value; i++)
{
markup += "<tr>";
for(j=0; j<nColumns.value; j++)
{
markup += "<td width=50 height=50> </td>";
}
markup += "</tr>";
}
markup = "</table>";
spaceofDiv.innerHTML = markup;
Try some thing this. Use a avariable add all string in to it and then set innerhtml. Als oyou are not closing the tr
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
var tableStr = "";
tableStr =("<table border=1>");
for(i=0; i<nRows.value; i++)
{
tableStr +="<tr>";
for(j=0; j<nColumns.value; j++)
{
tableStr +="<td width=50 height=50></td> ";
}
tableStr +="</tr>";
}
tableStr += "</table>"
spaceofDiv.innerHTML=tableStr;
}

Categories

Resources