I can't figure out why my horizontal borders are not showing up with my output section. See code and screenshot below:
I would like to have horizontal borders and if possible keep the date fields from
wrapping into the next row below itself.
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
<td align="center"><input type="button" value="Submit" name="submit" id="submit" onClick="display()" /></button></td>
</tr>
</table>
<table width="400px" align="center" colspan="40" table border="5">
<tr style="background-color:#8FBC8F;">
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
<tr>
<td align="center"><div id="displayarea"></div></td>
<td align="center"><div id="displayarea1"></div></td>
<td align="center"><div id="displayarea2"></div></td>
<td align="center"><div id="displayarea3"></div></td>
<td align="center"><div id="displayarea4"></div></td>
</tr>
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
function getValue() {
var Items = "";
var td1 = document.getElementById("displayarea").innerHTML.split("<br>");
var td2 = document.getElementById("displayarea1").innerHTML.split("<br>");
var td3 = document.getElementById("displayarea2").innerHTML.split("<br>");
var td4 = document.getElementById("displayarea3").innerHTML.split("<br>");
var td5 = document.getElementById("displayarea4").innerHTML.split("<br>");
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
document.getElementById("displayarea").innerHTML += document.getElementById("fname").value + "<br />";
document.getElementById("fname").value = "";
document.getElementById("displayarea1").innerHTML += document.getElementById("lname").value + "<br />";
document.getElementById("lname").value = "";
document.getElementById("displayarea2").innerHTML += document.getElementById("sname").value + "<br />";
document.getElementById("sname").value = "";
document.getElementById("displayarea3").innerHTML += document.getElementById("pname").value + "<br />";
document.getElementById("pname").value = "";
document.getElementById("displayarea4").innerHTML += document.getElementById("jname").value + "<br />";
document.getElementById("jname").value = "";
}
I highly suggest you start separating your data from your presentation of that data.
So, split your display function into two: createRow and renderRows. Likewise, getValues can just be getRows.
Note that this required a different way of doing things in your code, so I also refactored your HTML and CSS to bring it more in line with modern methods.
function getRows(data) {
return data.map(datum => Object.values(datum).join(',')).join('\n');
}
function createRow(data) {
const datum = {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value,
sname: new Date(document.getElementById("sname").valueAsNumber).toLocaleString(),
pname: new Date(document.getElementById("pname").valueAsNumber).toLocaleString(),
jname: document.getElementById("jname").value
};
data.push(datum);
document.getElementById("dataForm").reset();
renderRows(data);
}
function renderRows(data) {
const body = document.getElementById("renderedData");
body.innerHTML = "";
for (let datum of data) {
let tr = document.createElement('tr');
let tdFName = document.createElement('td');
tdFName.appendChild(document.createTextNode(datum.fname));
tr.appendChild(tdFName);
let tdLName = document.createElement('td');
tdLName.appendChild(document.createTextNode(datum.lname));
tr.appendChild(tdLName);
let tdSName = document.createElement('td');
tdSName.appendChild(document.createTextNode(datum.sname));
tr.appendChild(tdSName);
let tdPName = document.createElement('td');
tdPName.appendChild(document.createTextNode(datum.pname));
tr.appendChild(tdPName);
let tdJName = document.createElement('td');
tdJName.appendChild(document.createTextNode(datum.jname));
tr.appendChild(tdJName);
body.appendChild(tr);
}
}
window.addEventListener('load', () => {
const data = [];
document.getElementById('add').addEventListener('click', function(e) {
createRow(data);
});
document.getElementById('getData').addEventListener('click', function(e) {
console.log(getRows(data));
});
});
form {
width: max-content;
margin: 0 auto 1rem;
}
.control-group {
display: flex;
justify-content: space-between;
}
fieldset {
display: flex;
flex-flow: column nowrap;
}
fieldset button {
align-self: flex-end;
}
<form id="dataForm">
<fieldset>
<legend>Enter Data</legend>
<div class="control-group">
<label for="fname">Name:</label>
<input id="fname" type="text">
</div>
<div class="control-group">
<label for="lname">Company:</label>
<input id="lname" type="text">
</div>
<div class="control-group">
<label for="sname">Time In:</label>
<input id="sname" type="datetime-local">
</div>
<div class="control-group">
<label for="pname">Time Out:</label>
<input id="pname" type="datetime-local">
</div>
<div class="control-group">
<label for="jname">Description of Work:</label>
<textarea id="jname"></textarea>
</div>
<button type="button" id="add">Add</button>
</fieldset>
</form>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody id="renderedData">
</tbody>
</table>
<button type="button" id="getData">Get Data</button>
To get borders for all cells, add this at the top of your html code (inside the head):
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid #555;
}
</style>
Adjust the border thickness, style and color as you like (in the border setting of td)
Here's an easy way to add a row with each addition using the element - available in all good browsers (not so fast Internet Explorer, I wasn't talking to you)
I've also changed how to read the values
note, using class instead of id in the cells in the rows - to make it easy to get them all with minimal change to your code
Although, personally I'd get the row data data differently (shown in alternativeGetValues)
function getValue() {
var Items = "";
var td1 = [...document.querySelectorAll(".displayarea")].map(e => e.innerHTML);
var td2 = [...document.querySelectorAll(".displayarea1")].map(e => e.innerHTML);
var td3 = [...document.querySelectorAll(".displayarea2")].map(e => e.innerHTML);
var td4 = [...document.querySelectorAll(".displayarea3")].map(e => e.innerHTML);
var td5 = [...document.querySelectorAll(".displayarea4")].map(e => e.innerHTML);
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ,";
if (td5[i])
Items += td5[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
const template = document.getElementById("row");
const clone = template.content.cloneNode(true);
const additem = (dest, src) => {
const s = document.querySelector(src);
clone.querySelector(dest).innerHTML = s.value;
s.value = "";
};
additem(".displayarea", "#fname");
additem(".displayarea1", "#lname");
additem(".displayarea2", "#sname");
additem(".displayarea3", "#pname");
additem(".displayarea4", "#jname");
template.insertAdjacentElement('beforebegin', clone.firstElementChild);
}
// IMHO this is better
function alternateGetValue() {
const Items = [...document.querySelectorAll('.data')]
.map(row => [...row.querySelectorAll('td>div')]
.map(d => d.textContent).join(',')
).join('\n');
console.log(Items);
return Items;
}
.wide {
min-width:12em;
}
F: <input id="fname"> <br>
L: <input id="lname"> <br>
S: <input id="sname"> <br>
P: <input id="pname"> <br>
J: <input id="jname"> <br>
<input type="button" value="add" onclick="display()"/>
<input type="button" value="show" onclick="getValue()"/>
<input type="button" value="Better" onclick="alternateGetValue()"/>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center" class="wide"><b>Time In</b></td>
<td align="center" class="wide"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody>
<template id="row">
<tr style="background-color:#8F8FBC;" class="data">
<td align="center"><div class="displayarea"></div></td>
<td align="center"><div class="displayarea1"></div></td>
<td align="center"><div class="displayarea2"></div></td>
<td align="center"><div class="displayarea3"></div></td>
<td align="center"><div class="displayarea4"></div></td>
</tr>
</template>
</tbody>
</table>
Related
I have a dynamic table and when i add a row i want to save the data from input.
I can save the data but all inside one array,i want to set just 3 values each sub array.
Because one row have 3 inputs.
But i´m having some difficulties.
I'm new to javascript and here at stack overflow
Can you help me please?
function arraySaveData() {
var data = [];
for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function (_, element) {
var element = document.getElementsByName("namesavedata[]");
for (var i = 0; i < element.length; i++) {
data.push(element[i].value);
}
});
var result = [];
for(var i = 0; i < data.length; i++) {
var obj = {}
obj= data[i];
result.push(obj)
}
console.log(result)
}
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr name="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_2" placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar dados da tabela
</button>
</div>
</div>
Your issue is that you are creating an object and then reassigning it to the value of data[i]. This is then being pushed to your array, rather than an object, so you are getting an array of values rather than an array of objects.
Change this line of code:
var obj = {};
obj = data[i];
result.push(obj); // Add data[i] to the results array.
To this:
var obj = {data[i]};
result.push(obj); // Add an object containing data[i] to the results array
Now, you are pushing the object with the value of data[i] inside.
Or if you want to have three sub-arrays as in your question:
var tableCell = [data[i]];
result.push(tableCell);
If you run this code snippet, you can see what's happening when you reassign obj to data[i]:
const data = ["foo","bar"];
var obj = {};
console.log(obj);
// output: {}
obj = data[0];
console.log(obj);
// output: "foo"
I am just starting to program with javascript and I ran into this difficulty:
I created a dynamic table in html and javascript. I have already created the function to add rows and delete.
But I am having some difficulty in saving the received data into the array. It only saves the first row into the array. I want it to loop and save all the respective data in the array.
type here
My html code:
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr id="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata1[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata2[]" id="val_2"placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata3[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar
</button>
</div>
</div>
My Javascript code:
function arraySaveData() {
var data = [];
//var dataMain = [];
//for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function () {
data.push({
verticePolig: $('input[name="namesavedata1[]"]').val(),
});
data.push({
coordM: $('input[name="namesavedata2[]"]').val(),
});
data.push({
coordP: $('input[name="namesavedata3[]"]').val(),
});
});
console.log(data);
//dataMain.push(data);
//}
//console.log(dataMain);
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata1[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata2[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata3[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
The problem is in the loop you have to add the data. You always take the same 3 inputs in each loop.
You should receive the current element in the callback function for each loop it makes, something like the example below:
$('#mytableform1').each(function (_, element) {
// element is the current row <tr id="allDataRow">
// now you find children element value
const verticePolig = $(element).find('namesavedata1[]').val()
const coordM = $(element).find('namesavedata2[]').val()
const coordP = $(element).find('namesavedata3[]').val()
data.push({
verticePolig,
coordM,
coordP
})
});
I am fairly new to javascript so any assistance is appreciated. I am trying to collect 2 related inputs from a user and display the array object as a table. When the inputs are submitted however, the array is displaying as undefined. I am not sure where I am going wrong. Any suggestions?
I have tried different methods of collecting the inputs off the form but none seem to work.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Example:</title>
<script type="text/javascript">
var flights = [];
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
function render() {
document.getElementById("mydiv").innerHTML = "";
thelisthtml = "";
for(i = 0; i< flights.length; i++)
thelisthtml += "<div class='card' id="+ i +"><div class='card-body'>";
thelisthtml += "Flight " + (i+1) + " : " + flights[i] + " " + "<button type='submit' onclick = 'clearToDo(this)' id="+ i +">Remove From List</button>";
document.getElementById("mydiv").innerHTML = thelisthtml;
}
function calculateStatus(){
var totalMiles = Number(document.getElementById("totalMiles").value);
if (miles < 9999){
tr = document.getElementById("table").rows[1];
tr.style.backgroundColor = "yellow";
}
if (miles >= 10000 && miles <= 24999){
tr = document.getElementById("table").rows[2];
tr.style.backgroundColor = "yellow";
}
if (miles >= 25000){
tr = document.getElementById("table").rows[3];
tr.style.backgroundColor = "yellow";
}
}
function refreshPage() {
window.location.reload();
}
</script>
</head>
<body>
<br>
<table id="table" border ="1">
<tr>
<th>Medallion Status</th>
<th>Level</th>
</tr>
<tr>
<td>Bronze</td>
<td> < 10000 miles</td>
</tr>
<tr>
<td>Silver</td>
<td> < 25000 miles</td>
</tr>
<tr>
<td>Gold</td>
<td> > 25000</td>
</tr>
</table>
<h1><strong>Traveler Information </strong></h1><br> <br>
Flight Number: <input type="text" id="number" name="number" value="" />
<br> <br>
Miles Flown: <input type="text" id="miles" name="miles" value=""/> <br>
<br>
<input type="submit" value="Add Flight" id="go" onclick="add(this)"/>
<p>----------------------------</p>
<table>
<thead>
<tr>
<th>Flight</th>
<th>Miles</th>
</tr>
<thead>
<tbody>
<tr class="col-md-6" id="mydiv"></tr>
</tbody>
</table>
<input type="reset" id="reset" name="Reset" value="Reset"
onclick="refreshPage()" /> <br> <br> <br>
<br> <br>
</body>
</html>
the expected result is the array will display in a table as the user enters information. the actual result is the array is undefined.
There are several issues but the answer to your question about how to fix the flights array containing undefined is to change
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
to
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push(numberElem.value, milesElem.value);
render();
numberElem.value = "";
milesElem.value = "";
}
In your original add function you are pushing number and miles onto the flights array but number and miles are undefined variables so you are pushing undefined and undefined onto the flights array.
To also fix the other issues I'd suggest replacing your add and render functions with the follow
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push({
number: numberElem.value,
miles: milesElem.value});
render();
numberElem.value = "";
milesElem.value = "";
}
function render() {
const tbody = document.querySelector('#outputTable tbody');
tbody.innerHTML = flights.map((flight, i) => {
return ''
+ '<tr>'
+ '<td>'
+ flight.number
+ '</td>'
+ '<td>'
+ flight.miles
+ '</td>'
+ '<td>'
+ `<button type='button' onclick="clearToDo(${i})">`
+ 'Remove From List'
+ '</button>'
+ '</td>'
+ '</tr>';
}).join('');
}
and changing your second <table> to <table id="outputTable">.
I have an html code with multiple rows containing two values.Using javascript,I am able to compare the two values for only one row.How can I do the same for dynamically generated rows.
HTML:
<tbody id="appendrow" class="appendrow">
<input type="text"
data-field="quantity"
required
class="form-control"
name="units_ordered[]"
id="units_ordered0"
value=""/>
<input type="text"
data-field="inventory"
class="form-control"
name="inventory"
id="inventory0"
value="" />
</tbody>
Javascript:
var counter = 1;
$(window).load(function () {
$(function () {
$('#addRow').click(function () {
var row = $(' <tbody id=\'appendrow\' class=\'appendrow\'><tr><td> <input type=\'text\' required class=\'form-control\' name=\'sku[]\' onclick=\'filtersku(this,' + counter + ');\'> <input type=\'hidden\' id=\'product_id' + counter + '\' name=\'product_id[]\'/></td> <td> <input type=\'text\' readonly data-field=\'vendorsku\' id=\'vendor_sku' + counter + '\' name=\'vendorsku[]\'class=\'form-control\'></td> <td><input class=\'form-control\' data-field=\'quantity\' type=\'text\' required id=units_ordered' + counter + '\' name=\'units_ordered[]\' /></td> <td><input class=\'form-control\' type=\'text\' data-field=\'price\' required name=\'vendor_unit_price[]\' id=\'vendor_price' + counter + '\'></td> <td><input name=\'discount_percent[]\' data-field=\'discount\' class=\'form-control\' ><input type=\'hidden\' data-field=\'discountnumber\' class=\'form-control\' id=\'discountnumber\' ></td><td><input type=\'text\' readonly data-field=\'tax\' id=\'tax_id' + counter + '\' class=\'form-control\' name=\'tax_id[]\' /></td><td> Rs. <span data-field=\'taxPrice\' id=\'taxPrice' + counter + '\' >0</span><input type=\'hidden\' data-field=\'taxPriceInput\' id=\'taxPriceInput' + counter + '\' class=\'taxPrice\' value = \'0\'/> </td> <td><input type=\'text\' class=\'form-control\'data-field=\'total\' name=\'subtotal[]\'/><input type=\'hidden\' data-field=\'totalbeforetax\' class=\'form-control\' id=\'subtotalbeforetax\' /></td><td><button type=\'button\' class=\'btn btn-danger\' name=\'delete[]\' onclick=\'javascript:deletefun(this);\'><i class=\'fa fa-trash\' aria-hidden=\'true\'></i></button></td></tr></tbody>');
$('#example').append(row);
counter++;
});
});
});
function validation() {
var ordered = parseInt(document.getElementById('units_ordered0').value);
var inventory = parseInt(document.getElementById('inventory0').value);
if (inventory == -1) {
return true;
}
else {
if (ordered <= inventory) {
return true;
}
else {
document.getElementById('error').innerHTML = ('Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory).fontcolor('red');
return false;
}
}
}
Please note the correct structure of the HTML5 Table. Here is a clean HTML5 Table structure:
<table>
<caption>Table Caption</caption>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Header Row 1</th>
<th>Header Row 2</th>
<th>Header Row 3</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer Row 1</td>
<td>Footer Row 2</td>
<td>Footer Row 3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Body Row 1</td>
<td>Body Row 2</td>
<td>Body Row 3</td>
</tr>
</tbody>
</table>
And about your question:
var counter = 1;
document.getElementById( 'addRow' ).addEventListener( 'click', function ( e ) {
var table = document.getElementById( 'myTable' ),
row = table.insertRow( counter ),
cell1 = row.insertCell( 0 ),
cell2 = row.insertCell( 1 );
cell1.innerHTML = '<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered' + counter + '" required/>';
cell2.innerHTML = '<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory' + counter + '"/>';
counter++;
e.preventDefault()
} )
document.getElementById( 'validate' ).addEventListener( 'click', function ( e ) {
validation();
e.preventDefault()
} )
function validation() {
var ordered = document.querySelectorAll( 'input[id^="units_ordered"]' ),
inventory = document.querySelectorAll( 'input[id^="inventory"]' );
document.getElementById( 'error' ).innerHTML = ''
ordered.forEach( function ( item, index ) {
var ordered_val = Number( item.value ) || 0,
inventory_val = Number( inventory[ index ].value ) || 0
if ( inventory_val == -1 ) {
return true
} else {
if ( ordered_val <= inventory_val ) {
return true
} else {
document.getElementById( 'error' ).innerHTML += 'Row ' + +( index + 1 ) + ': Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory_val + '<br/>';
return false
}
}
} )
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 300px
}
td, th {
border: 1px solid #86af49;
text-align: left;
padding: 0
}
th {
padding: 5px;
color: #fff;
background-color: #86af49
}
input[type="text"] {
box-sizing: border-box;
width: 100%;
border: 0;
outline: none
}
#error {
color: red;
font-size: .75em
}
<p>
<button type="button" id="addRow">Add Row</button>
<button type="button" id="validate">Validation</button>
</p>
<table id="myTable">
<thead>
<tr>
<th>Ordered</th>
<th>Inventory</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered0" required/>
</td>
<td>
<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory0"/>
</td>
</tr>
</tbody>
</table>
<p id="error"></p>
I am trying to print my object that holds my inputName field and my inputDate field. I am successfully storing both variables onto my localStorage but I am unable to print it in my table. I am proving a picture to a better understanding. I tried to use console.log but It doesn't print anything in the console. I guess I do not know how to use console log.
What I am trying to do is the following : once an user inputs a name and date, I want to be able to display those values to my table.
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
for (var i = 0; I < JsObject.length; i++) {
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>";
//console.log(JsObject);
}
}
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table id="myTable" >
<tr>
<th>Name</th>
<th>Date</th>
<th>Endorsement</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
</head>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</body>
</html>
Try This:
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
//for (var i = 0; I < JsObject.length; i++) {
/*
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>"; */
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + JsObject[i].nameInput + "</td>");
tr.append("<td>" + JsObject[i].dateInput + "</td>");
tr.append("<td>" + next_variable + "</td>");
$('myTable').append(tr);
}
//console.log(JsObject);
}
<html>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
</head>
<body>
<table id="myTable" >
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</html>