For example I have an initial value of 10,000 when I click the radio button which is "Minus" and I enter a value of 1000 the initial value will become 9000. And when I click the radio button "Add" and I enter a value of 2000
current initial which is 9000 + 2000 is equal to 11,000.
The problem is the initialValue back to it's original value which is 10,000.
//external script
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;
this.addNum = function() {
alert(this._initialNum = this._initialNum + this._numOne);
return this._initialNum;
};
this.minusNum = function() {
alert(this._initialNum = this._initialNum - this._numOne);
return this._initialNum;
};
}
//body script
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
function printResult() {
var initialValue = 10000, deposit = 0, withdraws = 0;
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
var objAccount = new Compute(initialValue, numOne);
if (rdoAdd.checked) {
deposit += objAccount.addNum();
display = "<tr>";
display += "<td>" + deposit + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
withdraws += objAccount.minusNum();
display = "<tr>";
display += "<td>" + withdraws + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<!--
Withdraw<br><br>
<input type="text" id="txtNumTwo">
-->
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
Just move
var initialValue = 10000;
var objAccount = new Compute(initialValue);
outside of the printResult function.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src = "java.js"></script>
<script>
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
var initialValue = 10000;
var objAccount = new Compute(initialValue);
function printResult() {
var display = "";
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
if (rdoAdd.checked) {
objAccount.addNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialValue + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialValue + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
function Compute(initialNum) {
this._initialNum = initialNum;
this.addNum = function(numOne) {
alert(this._initialNum = this._initialNum + numOne);
return this._initialNum;
};
this.minusNum = function(numOne) {
alert(this._initialNum = this._initialNum - numOne);
return this._initialNum;
};
}
This is just a scope related issue. If you use var inside the function, it'll redeclare or create a new instance of initialValue in local scope.
If you want to change the value of variable initialValue, then don't use var. This will only change the variable defined in the global scope...
This works since the JavaScript interpreter firstly checks if there is an instance of the given variable in the local scope or not. If not, then it will check the existence of the variable in global scope.
EDIT :
As per your problem, you want the value of initialValue to persist after each calculation. In order to achieve this, you must first declare the object objAccount in the global scope outside the printResult() function; since in the code, every time the function printValue() is called, a new instance of Compute (objAccount) is being created. Secondly, you should remove the numOne attribute from Compute class and instead pass numOne as a parameter to addNum() and minusNum().
You can modify the methods of Compute as:
this.addNum = function(_numOne) {
...
}
this.minusNum = function(_numOne) {
...
}
And while calling the methods,
objAccount.addNum(<some_number>);
and
objAccount.minusNum(<some_number>);
After this, you need not even use deposit or withdraws...
if (rdoAdd.checked) {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
Similarly, do the same with the else statement...
Bonus: You seem to be using ES5 style, instead use ES6 (includes keywords like class & let: similar to var)
Here's a snippet (using ES6 classes)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src = "java.js"></script>
<script>
class Compute {
constructor(initialNum) {
this._initialNum = initialNum;
}
addNum(_numOne) {
alert(this._initialNum += _numOne);
return this._initialNum;
};
minusNum(_numOne) {
alert(this._initialNum -= _numOne);
return this._initialNum;
};
}
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
var initialValue = 10000;
var objAccount = new Compute(initialValue);
function printResult() {
var display = "";
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
if (rdoAdd.checked) {
objAccount.addNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
Related
I'm new to both Progress and JavaScript. I'm getting elements from a temp-table in Progress using json. I'll show part of my code.
$.post({
url: gWS + "/bass/bass054.p",
data: {
"process": "<?php echo $process; ?>"
},
success: function(data){
var table = document.getElementById("table");
var j = 0;
var dataProc = "";
var qtProc = 0;
var item = "";
var sumQt = 0;
var qt_total = 0;
var idGrp = "";
for (var i = 0; i < data["tt-base"].length; i++) {
var row = table.insertRow(j+2);
if (data["tt-base"][i]["cod_id_bloco_edi"] != idGrp && i>=2) {
if (sumQt == qt_total) {
row.style.background = "green";
} else {
row.style.background = "#ff0000";
}
row.insertCell(0).innerHTML = "<b>QT TOTAL:</b>";
row.insertCell(1).innerHTML = "<b>" + item + "</b>";
row.insertCell(2).innerHTML = "<b>" + sumQt + "</b>";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<b>" + qt_total + "</b>";
sumQt = 0;
j++;
row = table.insertRow(j+2);
}
if (data["tt-base"][i]["cdn_segment_edi"] == 44) {
row.style.background = "#00ff00";
dataProc = data["tt-base"][i]["dsl_dados_entr_edi"].substring(7,9) + "/" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(5,7) + "/20" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(3,5) + "</div>";
qtProc = parseInt(data["tt-base"][i]["dsl_dados_entr_edi"].substring(11,20), 10) + "</div>";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = " ";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
j++;
sumQt = parseInt(sumQt,10) + parseInt(qtProc,10);
} else if (data["tt-base"][i]["cdn_segment_edi"] == 446) {
if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("PRE") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#0099CC";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "PREVIS";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
} else if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("FIR") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#00ff00";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "FIRM";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
}
}
idGrp = data["tt-base"][i]["cod_id_bloco_edi"];
}
}
}).fail(function() {
alert("Not Possible.");
})
So, instead of deleting the row as I'm doing it now I'd like to replace the previous only the cells with the FIRM and PREVIS. I tried using only row.insertCell(2).innerHTML = "PREVIS"; but it didn't work correctly.
Is there any suggestion as to how can I do it? Sorry if I'm not clear enough as i'm new to all this. Thanks for your time.
I managed to do what I wanted after tweaking for hours, lol.
Instead of using insertRow or insertCell, I just used the following
table.rows[j+2].style.background = "#0099CC";
table.rows[j+2].cells[2].innerHTML = "PREVIS";
This way, I was able to replace the content of what I wanted. I still have to change some other details, but the most difficult part is finally gone. Sorry if I wasted your time, but writing here has helped me to see the code in a different angle. I hope my code can help other people.
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br>
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src="java.js"></script>
<script>
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
//constructor function
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
//javascript in the body tag
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br> //rdo for Add
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br> //rdo for Subs
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function printResult() {
var display = "";
var initialValue = 10000;
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
display = "<tr>";
display += "<td>" + (personList[i].addNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
display = "<tr>";
display += "<td>" + (personList[i].minusNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
}
//Constructor Function
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;
this.addNum = function() {
this._initialNum += this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum -= this._numOne;
return this._initialNum;
};
}
Since HTTP is stateless and you want to perform operations on 2 different actions, you will need to store the result of each action in some place. For the simplest example, you can create hidden field on your HTML page. This can have value of 10000 when your HTML is loaded for the first time and update it’s value after each action is executed.
Let’s assume you have following hidden field on your HTML:
<input type=“hidden” id=“persistedResult” value=“10000” />
Here is your updated printResult method:
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById(‘persistedResult’).value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById(‘persistedResult’).value = newValue;
}
Note: This is a primitive example to guide you how to achieve data persistence. Generally, the data will be persisted on server.
This code takes care of scenario where there is only one person in the list, which is the approach in your current code example. You will need to enhance the logic if you want to have this working on an array of persons.
var valueEl = document.getElementById('value');
var addEl = document.getElementById('add');
var resultEl = document.getElementById('result');
var calculateEl = document.getElementById('calculate');
var initialValue = 1000;
function appendResult(result) {
var liEl = document.createElement("li");
liEl.innerHTML = result;
resultEl.appendChild(liEl);
}
function handleClickCalculate() {
var operand = addEl.checked ? 1 : -1;
var value = +valueEl.value * operand;
initialValue += value
appendResult(initialValue);
}
calculateEl.addEventListener('click', handleClickCalculate)
appendResult(initialValue);
jsFiddle
Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good
I have a query in javascript.. Please check the below image
In Above image :
First Input Box is Description
2nd Input Box is Qty
3rd is Value
I have got total qty using below script onchange of textbox :
function findTotal(){
var total = 0;
var $changeInputs = $('input.qtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
$("#totalvval").val(total);
}
I have got total Value using below :
function qfindTotal(){
var total = 0;
var $changeInputs = $('input.qqtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.qtotal').text(total);
$("#totalqval").val(total);
if(total>10000){
alert("Amount should not be greater than 10000");
}
}
My query is that we need total of qty x value + qty x value + qty x value =total
You can try something like this:
Fiddle
Code
function createHTML() {
var html = "";
for (var i = 0; i < 3; i++) {
html += "<input type='text' class='qty' id='txtQty_" + i + "' onblur='updateTotal()' />";
html += "<input type='text' class='cost' id='txtQty_" + i + "' onblur='updateTotal()'/>";
html += "<br/>"
}
html += "Qty Total: <span id='qty_total'>0</span>";
html += "Cost Total: <span id='cost_total'>0</span>";
document.getElementById("content").innerHTML = html
}
function updateTotal() {
var qty = document.getElementsByClassName("qty");
var cost = document.getElementsByClassName("cost");
var total_qty = 0;
var total_cost = 0;
for (var i = 0; i < qty.length; i++) {
if (qty[i].value && cost[i].value) {
total_cost += qty[i].value * cost[i].value;
total_qty += parseInt(qty[i].value);
}
}
document.getElementById("qty_total").innerHTML = total_qty;
document.getElementById("cost_total").innerHTML = total_cost;
}
(function() {
createHTML();
})()
<div id="content"></div>
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>";