document.getElementById.innerHTML does not write anything ..? - javascript

My Problem:
document.getElementById("values").innerHTML does not write anything. If I try to do document.getElementById("values").innerHTML = "stuff"; (just with a String) - nothing happens.
What am I doing wrong here?
HTML:
<form onsubmit="save_entry();return false;">
<label for="i_km">Kilometer: <input type="text" name="km" id="i_km"></label><br>
<label for="i_fuel">Sprit: <input type="text" name="fuel" id="i_fuel"></label><br>
<input type="submit" value="Save" />
</form>
<div id="values"></div>
JavaScript:
function save_entry() {
var anzahl = localStorage.length/2;
var nameKeyKm = "k" + anzahl;
localStorage.setItem(nameKeyKm,document.forms[0]["km"].value);
var nameKeyF = "F" + anzahl;
localStorage.setItem(nameKeyF,document.forms[0]["fuel"].value);
document.write("Entry saved!")
}
function show_entry() {
document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for (var i = 0; i < localStorage.length/2; i++) {
alert("d");
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML = "<tr>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML = "</tr>";
}
document.getElementById("values").innerHTML = "</table>";
}
show_entry();

This does work!
function show_entry(){
var content = '';
content = content + '<table><th>Kilometer</th><th>Getankt</th>';
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
content = content + "<tr>";
content = content + "<td>"+localStorage.getItem(temp_km)+"</td>";
content = content + "<td>"+localStorage.getItem(temp_f)+"</td>";
content = content + "</tr>";
}
content = content + "</table>";
document.getElementById("values").innerHTML = content;
}

innherHTML is an attribute, so everytime you write document.getElementById('id').innerHTML = '...' you are actually changing the value of innerHTML to that thing, not concatenating it.
So writing document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>"' changes the value of innerHTML to "<table><th>Kilometers</th><th>Tanked</th>"', and, afterwards, you replaced this value for <tr>, then for <td>...</td> and so on...
You clearly want to create a table. Therefore, you should be concatenating the strings, using +=, like this:
function show_entry() {
document
.getElementById("values")
.innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";
}
document.getElementById("values").innerHTML += "</table>";
}
show_entry();

Each time you do
document.getElementById("values").innerHTML = "...";
you will replace the html inside the div with ID 'values'
So calling it multiple times with different values doesn't make sense.
You would either call it once and setting the whole innerHTML at once, like this
document.getElementById("values").innerHTML = "<tr><td>....etc...</td></tr>";
If you would call innerHTML sequentially you would do it as follows (which is just how to append any string in javascript), but in the comments below I just learned this should not be done like this:
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";

Related

Creating a table through local storage data?

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>

javascript to create table php mysql to save data

I need a table where the user enters how many rows and columns needed, they enter the numbers and the next page creates the table.
They will enter the info which will be saved into a database. The only way I can think to do this is with dynamic tables, is there a better way? Here is some super basic code, I haven't worked out the full table, wanted to get feedback before I continue in case there is a better way and I need to change course.
Simple form:
How many rows <input type="number" id="rowNumber"/><br>
How many columns <input type="number" id="colNumber"/><br>
<button onclick="myFunction()">Checkout</button>
function myFunction() {
var rowNumber = document.getElementById('rowNumber').value;
var colNumber = document.getElementById('colNumber').value;
window.location.href = "website/test.php?rowNumber="+rowNumber+"&colNumber="+colNumber;
}
test.php
<?php
$rowNumber=$_GET['rowNumber'];
$colNumber=$_GET['colNumber'];
?>
<script>
var numRows = "<? echo $rowNumber ?>";
var numCols = "<? echo $colNumber ?>";
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < numRows; row += 1) {
tableString += "<tr onclick=\"fnselect(this)\"<? if($rowID == "A") { echo "class ='selected'";} ?>>";
for (col = 1; col < numCols; col += 1) {
tableString += "<td>" + "R" + row + "C" + col + "" + "<input type='text' />" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
</script>
Looking into jQuery DataTables. A lot of nice functionality in there.
You can either bind to a JSON data source, or create your own rows manually like this URL:
https://datatables.net/examples/api/add_row.html
So, to use this, you have to reference jquery AND the data tables script. You'll have to either reference them from their given URLs, or download the scripts (I recommend the latter otherwise you create references to outside servers).

How to create a table in JS

I need to create a table in JS and show it in the page but it does not seem to work. I have two functions, the first one to actually create the table and the second one to order the elements in the table. I tried creating a simple div in html with id showlist but the table does not appear in the page. Please see the code below.
function myfunction() {
var array2 = [];
var list = "<table border ='1'>";
array2.sort(order);
list = list + "<tr>";
list = list + "<td colspan = '2'> TABLE </td>";
list = list + "</tr>";
list = list + "<tr>";
list = list + "<td> PRICE</td>";
list = list + "</tr>";
for (i = 0; i <= array2.length; i++) {
list = list + "<tr>";
list = list + "<td>" + array2[i].name + "</td>";
list = list + "<td>" + array2[i].price + "</td>";
list = list + "</tr>";
}
list = list + "</table>";
$("#showlist").html(list);
}
function order(n1, n2) {
if (n1.price > n2.price) {
return 1;
} else {
if (n1.price < n2.price) {
return -1;
} else {
return 0;
}
}
}
Your for loop <= runs from 0 to array2.length, it should be < - from 0 to array2.length-1.
for (i = 0; i < array2.length; i++) {
// ^_ Notice change here
...
}
Else, the last iteration would throw undefined errors.
Uncaught TypeError: Cannot read property 'name' of undefined
Fiddle Example

Dynamically assign unique id from var value in Javascript, jquery

In my program, I use javascript to generate a table which is then appended to the html document:
var html = "<table>";
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
I want each of the input elements to have a unique ID -- specifically a number. I was hoping to have a variable that is initialized to 1, which gets incremented each time a TD element is created. The value of this variable would be used as the input element ID. I haven't found any way to do this specifically. Thanks in advance!
Try this:
var html = "<table>";
var index=0;
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input id='img"+(index++)+"' type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try to add a global variable let count and increment it in inner loop, like,
var html = "<table>";
var count=1;// use this variable in inner for loop and increment it by 1
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++){
html += "<td class=\"covered\">\
<input id='"+(count++)+"' type=\"image\" src=\"imageURL.com\"/>\
</td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try this code:
html += "<td id='td-" + c +"'class=\"covered\"><input value='td-" + c +"' type=\"image\" src=\"imageURL.com"/></td>";
use this
var ID= new Date().getTime();

Appending Xml Data to List View JQuery Mobile

I am unable Show Parsed Response from Xml Service in JQuery Mobile List View. I unable to get were the Problem is,what i have Tried is.
First i took all the Response to theXML var then iam Trying to append to ListView Which i have Dynamically Created in javaScript Code. Here is my Code,
function processXML(theXML) {
var nodeTree = theXML.documentElement.getElementsByTagName('Employee');
var output = "";
output += "<ul data-role='listview' class='ui-listview'>";
var length = nodeTree.length;
for (var i = 0; i < length; i++) {
var empName = nodeTree[i].getElementsByTagName('name')[0].firstChild.nodeValue;
var empFName = nodeTree[i].getElementsByTagName('Fathername')[0].firstChild.nodeValue;
var empAddr = nodeTree[i].getElementsByTagName('Address')[0].firstChild.nodeValue;
output += buildRow(empName, empFName, empAddr);
}
output += "</ul>";
document.getElementById('result').innerHTML = output;
}
function buildRow(empName, empFName, empAddr) {
var row = "<li><a href='#'>";
row += empName;
row += empFName;
row += empAddr;
row += "</a></li>";
return row;
}
$("result").html(output).trigger("create");
$(".ui-listview").listview('refresh')‌​;

Categories

Resources