ow can I display images via url and it increments?
My table increments every time new data is stored. But how can I display image to my table?
The table already display the url I'm trying to display the image via url.
this is the output of my table https://firebasestorage.googleapis.com/v0/b/sad-police-app.appspot.com/o/October 21 16:9:15?alt=media&token=14866e4f-7a7b-4f11-a057-106313770861
<html>
<head>
<title>Firebase Realtime Database Web</title>
<script src="https://www.gstatic.com/firebasejs/5.5.1/firebase.js">
</script>
<script>
// Initialize Firebase
</script>
</head>
<body>
<div class="tablehead">
<h1>POLICE STATION 3</h1>
<table id="reports" border="1">
<tr>
<th>Case ID</th>
<th>Email Address</th>
<th>Caption</th>
<th>Location</th>
<th>Time</th>
<th>Picture</th>
</tr>
<tbody id="reportbody"></tbody>
</table>
</div>
<script>
var tblUsers = document.getElementById('reportbody');
var databaseRef = firebase.database().ref('PP3/');
var rowIndex = 1;
databaseRef.on('value', function(snapshot) {
tblUsers.innerHTML = '';
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(0);
var ccase= row.insertCell(0);
var email = row.insertCell(1);
var caption = row.insertCell(2);
var location = row.insertCell(3);
var time = row.insertCell(4);
var picture = row.insertCell(5);
ccase.appendChild(document.createTextNode(childData.CaseID.replace(/"/g, '')));
email.appendChild(document.createTextNode(childData.Email.replace(/"/g, '' )));
caption.appendChild(document.createTextNode(childData.Caption.replace(/\\/g, '').replace(/"/g, '')));
location.appendChild(document.createTextNode(childData.Location.replace(/\\/g, '').replace(/"/g, '')));
time.appendChild(document.createTextNode(childData.Time.replace(/"/g, '')));
picture.appendChild(document.createTextNode(childData.Picture.replace(/\\/g, '').replace(/"/g, '')));
rowIndex = rowIndex + 1;
});
});
</script>
</body>
</html>
Try this: SomeNode.appendChild(`<img src=${url}>`)
Related
I tried to access the elemnts created by handlebars by clicking on the buttons. but it takes first element it created. Please help me with this one
<body>
<div id="container"></div>
<div>
<table id="cartItem">
<tr>
<th>Product Name</th>
<th>count</th>
<th>Price</th>
<th>Id</th>
</tr>
</table>
</div>
<script type="text/x-handlebars-template" id="demo">
{{#each this}}
<h2 id="name">{{stock_name}}</h2>
<h2 id="id" style="display: none;">{{stock_id}}</h2>
<h4 id="price">{{stock_price}}</h4>
<button class="btn" onclick="placeOrder()"></button>
{{/each}}
</script>
<script src="Asset/js/Handle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js"></script>
<script src="Asset/js/placeOrder.js"></script>
</body>
Handle.js file contains code below,
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8080/api/stocks');
request.onload = function(){
if(request.status>=200 && request.status<400){
var data = JSON.parse(request.responseText);
createHTML(data);
}
else{
console.log("Error from server");
}
};
request.onerror = function(){
console.log("There is an error");
}
request.send();
function createHTML(jsonData){
console.log("testing.......")
console.log(jsonData);
var template = document.getElementById("demo").innerHTML;
var compiledTemplate = Handlebars.compile(template);
var GenerateHTML = compiledTemplate(jsonData);
var container = document.getElementById("container");
container.innerHTML= GenerateHTML;
}
Placeorder.js contains code below
function placeOrder(){
var i_Stocks = document.getElementById("name").textContent;
var i_price = document.getElementById("price").textContent;
var i_Id = document.getElementById("id").textContent;
console.log(i_Stocks);
console.log(i_price);
var table = document.getElementById("cartItem");
var row = table.insertRow(1);
var name = row.insertCell(0);
var count = row.insertCell(1);
var price = row.insertCell(2);
var id = row.insertCell(3);
name.innerHTML = i_Stocks;
price.innerHTML = i_price;
count.innerHTML = 1;
id.innerHTML = i_Id;
}
the Json request returns,
[{"stock_id":"stk0001","stock_name":"popsickle","stock_price":45,"stock_status":"yes"},{"stock_id":"stk0002","stock_name":"icecream","stock_price":66,"stock_status":"yes"},{"stock_id":"stk0003","stock_name":"oreo","stock_price":60,"stock_status":"yes"},{"stock_id":"stk0004","stock_name":"jellyBears","stock_price":40,"stock_status":"yes"},{"stock_id":"stk0005","stock_name":"cakes","stock_price":70,"stock_status":"no"}]
I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}
I am trying to add a table header only once on to the top of a table. I have a code where I am able to generate header after inserting a row. I am missing the indexing here. where I am able to add header only after inserting the second row. Could you please help me fix a minor error here. I would not want to pass any object from html page.
var table = document.getElementById("Table");
// Empty tables
while(table.rows.length > 0) {table.deleteRow(0);}
// Add rows
for (var i = 1; i<data.Contents.length; i++) {
var row = table.insertRow(i-1);
var cell1 = row.insertCell(0), cell2 = row.insertCell(1),cell3 = row.insertCell(2),cell4 = row.insertCell(3),cell5 = row.insertCell(4),cell6 = row.insertCell(5),cell7 = row.insertCell(6);
var cell8 = row.insertCell(7), cell9 = row.insertCell(8),cell10 = row.insertCell(9),cell11 = row.insertCell(10),cell12 = row.insertCell(11),cell13 = row.insertCell(12),cell14 = row.insertCell(13);
//Code for header
var header = document.getElementById("Table").rows[0].cells;
header[0].innerHTML = " ";
header[1].innerHTML = " ";
header[2].innerHTML = "<b>NAME</b>";
header[4].innerHTML = "<b>MODIFIED</b>";
header[6].innerHTML = "<b>TIME</b>";
header[8].innerHTML = " ";
header[10].innerHTML = "<b>MORE</b>";
header[12].innerHTML = " ";
//column1: file icon
var btn_fileIcon = document.createElement("input");
btn_fileIcon.setAttribute("type","image");
btn_fileIcon.setAttribute("src","images/file.png");
btn_fileIcon.setAttribute("style","height:20px;width:20px");
cell2.appendChild(btn_fileIcon);
// column2: file name
cell3.innerHTML = data.Contents[i].Key.replace(folderName+'/', '');//data.Contents[i].Key;
// Time
var str = dateModified( data.Contents[i].LastModified);
cell5.innerHTML = " " + str;
cell5.setAttribute("style","padding-left: 4cm");
cell5.setAttribute("position","fixed");
cell5.style.textAlign = "center";
// size
var s = Math.round( data.Contents[i].Size/1024);
var fileSize = s.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
cell7.innerHTML = fileSize + " KB";
cell7.setAttribute("style","padding-left: 4cm");
cell7.setAttribute("position","fixed");
cell7.style.textAlign = "center";
// column3: download (csv)
var btn_download = document.createElement("input");
btn_download.setAttribute("type","image");
btn_download.setAttribute("src","images/download-button.png");
btn_download.setAttribute("style","height:20px;width:20px;margin-left: 100px;margin-right: 10px;");
btn_download.setAttribute("onclick","load2local(this);");
btn_download.fileName = data.Contents[i].Key;
cell9.appendChild(btn_download);
// column4: delete
var btn_delete = document.createElement("input");
btn_delete.setAttribute("type","image");
btn_delete.setAttribute("src","images/close-browser.png");
btn_delete.setAttribute("style","height:20px;width:20px;margin-left: 10px;margin-right: 10px;");
btn_delete.setAttribute("onclick","deleteObj(this);");
btn_delete.fileName = data.Contents[i].Key;
cell11.appendChild(btn_delete);
// load to NB
var btn_load2NB = document.createElement("input");
btn_load2NB.setAttribute("type","image");
btn_load2NB.setAttribute("src","images/eye.png");
btn_load2NB.setAttribute("style","height:25px;width:25px;margin-left: 10px;margin-right: 10px;");
btn_load2NB.fileName = data.Contents[i].Key;
btn_load2NB.setAttribute("onclick","load2NB(this);");
btn_load2NB.fileSize = data.Contents[i].Size;
cell13.appendChild(btn_load2NB);
// checkbox
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "all");
checkbox.setAttribute("value", "ff");
checkbox.fileName = data.Contents[i].Key;
cell1.appendChild(checkbox);
checkbox.checked = false;
var element = document.createElement('hr');
// element.setAttribute("style","border: 1px solid black;text-align: left; margin-left: 2%; margin-right:2%;");
element.filename = data.Contents[i].Key;
cell14.appendChild(element);
}
Could you please help me to add a header once dynamically to a table?
This is one way to dynamically add table headers.
<html>
<script>
const tableHeaders = ['My Header1','My Header2','My Header3','My Header4'] // your header titles go here
function createNewTableHeader(headerTitle){
const temp = document.createElement('th');
temp.appendChild(document.createTextNode(headerTitle));
return temp
}
function addHeader() {
var tableHeaderPlaceHolder = document.getElementById('table-header-place-holder');
tableHeaders.forEach(header=>{
tableHeaderPlaceHolder.appendChild(createNewTableHeader(header));
})
}
document.addEventListener("DOMContentLoaded", function(event) {
addHeader();
});
</script>
<body>
<table id='table' cellspacing="20">
<tbody>
<tr id='table-header-place-holder'>
</tr>
</tbody>
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
</tr>
</tbody>
</table>
</body>
</html>
I can't sum the subtotals of an HTML column table using javascript. I need to sum the 5th column and put the result in a textbox so the costumer can see the totals of his bill. The thing is, I can't use database because it is a table that doesn't INSERT the value in the database until I hit the final button. Any help would be appreciated. Thanks a lot
var arr2 = "";
$('#añadir').click(function() {
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
var subtotal = (cantidad * punitario)
if (id_pla != "" && cantidad != "") {
var row = table.insertRow(cant);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = cant;
cell1.innerHTML = id_pla;
cell2.innerHTML = pla;
cell3.innerHTML = cantidad;
cell4.innerHTML = punitario;
cell5.innerHTML = subtotal;
cant++;
arr2 += id_pla + "," + cantidad + ","
$('#arr').val(arr2);
}
validar();
});
This is the HTML code
<table id="tablaC" class="table table-hover">
<thead>
<tr>
<th>ID Pedido</th>
<th>ID Plato</th>
<th>Plato</th>
<th>Cantidad</th>
<th>Precio Unitario</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<input id="arr" name="arr" value="" />
<br>
<br/>
<input class="btn btn-info" type="submit" value="Crear Registro" id="registro">
</form>
<p></p>
I notice several issues in your files codes, you should fix them in order to make this work:
1)
To compare with "" You should use strict equality "!==" instead of "!="
if (id_pla !== "" && cantidad !== "") {
instead of:
if (id_pla != "" && cantidad != "") {
2) "$" is not defined as a variable, unless you refer to jQuery.
/*here*/ $('#añadir').click(function() {
3) Ids missing in your HTML code:
Here you are saying:
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
But you are not giving any id to this elements on your html. It should be like this:
<th>ID Pedido</th>
<th id="plato_id">ID Plato</th>
<th id="plato_nombre">Plato</th>
<th id="cantidad">Cantidad</th>
<th id="plato_precio">Precio Unitario</th>
<th>Subtotal</th>
Hello I'm fairly new here so please correct me if I make any formatting or question errors!
I am attempting to create a simple shopping basket file and need some help getting the quantity of items within the basket to change. At the moment I can create a button that adds a new row to a table and fills it, I am just having a shortfall at getting the function to check if the item is already in the table and only update the quantity cell if it is. I am useless with IF statements, so any help would be more than appreciated!
<!DOCTYPE html>
<html>
<head>
<script>
function additem1() {
var table = document.getElementById("basket");
var row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = "Shorts (f)";
cell2.innerHTML = "Stone Wash";
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";
;
}
</script>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2> List of Items </h2>
<table border="1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<tr>
<td> Shorts (F) </td>
<td> Stone wash Denim shorts </td>
<td> 20 </td>
<td> 25.90 </td>
<td> <button onclick= "additem1()"> Add Item To Basket </button> </td>
</table>
<table id="basket" border = "1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<th colspan="2"> Add / Remove items </th>
</tr>
</table>
as you can see the first table holds the item information, and the second table holds the basket information.
Please consider to go deep on js coding; you can consider to check if the element already exist, then if so increment the quantity.
I made your code a little more generic, but for a working basket there is more to do, that's your job.
Code:
function additem1(e) {
var oRow = e.parentNode.parentNode
var prod = oRow.cells[0].innerHTML;
var des = oRow.cells[1].innerHTML;
var table = document.getElementById("basket");
var row1 = GetCellValues(prod);
if (typeof row1 === 'undefined') {
row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = prod;
cell2.innerHTML = des;
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";;
} else {
row1.cells[2].innerHTML = parseInt(row1.cells[2].innerHTML) + 1
}
}
function GetCellValues(prod) {
var table = document.getElementById('basket');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
if (table.rows[r].cells[c].innerHTML == prod) return table.rows[r];
}
}
return
}
Demo: http://jsfiddle.net/85o9yz02/