Beatified HTML code that is derived from database - javascript

I would like to Beautify the html code which I get from database.
Which is the best method to do this without using libraries.
I get this information from DB:
#{ var model = (Text.Alert.Models.AlertTemplateModel)Model; var contentItems = model.ContentItems.OrderByDescending(d => d.PublicationDate).ToArray(); } #for (int i = 0; i < contentItems.Count(); i++){ <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr valign="top"> #if (!String.IsNullOrEmpty(contentItems[i].MediaUrl)) { <td width="132"><img src="#(contentItems[i].MediaUrl)" style="display: block;" alt="" width="103"> </td> } <td> <font color="#7391a2" size="2"> <font color="#d1065a" size="3"> #if (!string.IsNullOrEmpty(contentItems[i].Url)) { #(contentItems[i].Title) } else { #(contentItems[i].Title) } </font> <br> #(Raw(contentItems[i].Description)) </font> </td> </tr> </tbody> </table> <br/> }";
This is my function:
function makeReadable(text) {
var readableHTML = text;
var lb = '\r\n';
//var htags = ["var", "#{", "#for", "#if", "#else", "}", "<img", "<html", "</html>", "</head>", "<title", "</title>", "<meta", "<link", "<style", "</style>", "</body>"];
var htags = ["var","#{","#for","#if","#else","}","<img", "<"];
for (i = 0; i < htags.length; ++i) {
var hhh = htags[i];
readableHTML = readableHTML.replace(new RegExp(hhh, 'gi'), lb + hhh);
}
var btags = ["</div>", "</span>", "</form>", "<a", "<font", "</fieldset>", "<br>", "<br />", "</a>", "<hr", "<pre", "</pre>", "<blockquote", "</blockquote>", "<ul", "</ul>", "<ol", "</ol>", "<li", "<dl", "</dl>", "<dt", "</dt>", "<dd", "</dd>", "<\!--", "<table", "</table>", "<caption", "</caption>", "<th", "</th>", "<tr", "</tr>", "<td", "</td>", "<script", "</script>", "<noscript", "</noscript>"];
for (i = 0; i < btags.length; ++i) {
var bbb = btags[i];
readableHTML = readableHTML.replace(new RegExp(bbb, 'gi'), lb + bbb);
}
var ftags = ["<label", "</label>", "<legend", "</legend>", "<object", "</object>", "<embed", "</embed>", "<select", "</select>", "<option", "<option", "<input", "<textarea", "</textarea>"];
for (i = 0; i < ftags.length; ++i) {
var fff = ftags[i];
readableHTML = readableHTML.replace(new RegExp(fff, 'gi'), lb + fff);
}
var xtags = ["<body", "<head", "<div", "<span", "<p", "<form", "<fieldset"];
for (i = 0; i < xtags.length; ++i) {
var xxx = xtags[i];
readableHTML = readableHTML.replace(new RegExp(xxx, 'gi'), lb + lb + xxx);
}
return readableHTML;
}
When I Use my Function the result is this:
#{ var model = (Text.Alert.Models.AlertTemplateModel)Model; var contentItems = model.ContentItems.OrderByDescending(d => d.PublicationDate).ToArray(); } #for (int i = 0; i < contentItems.Count(); i++) {
<table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody>
<tr valign="top"> #if (!String.IsNullOrEmpty(contentItems[i].MediaUrl)) {
<td width="132"><img src="#(contentItems[i].MediaUrl)" style="display: block;" alt="" width="103">
</td> }
<td>
<font color="#7391a2" size="2">
<font color="#d1065a" size="3"> #if (!string.IsNullOrEmpty(contentItems[i].Url)) {
<a href="#(contentItems[i].Url)">#(contentItems[i].Title)
</a> } else { #(contentItems[i].Title) } </font>
<br> #(Raw(contentItems[i].Description)) </font>
</td>
</tr> </tbody>
</table> <br/> }
";

Related

Javascript Interval continues endless without conditions met

var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>
Instruction___: doubleclick and hold
Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.
Im looking for a solution or a good way to adress the problem:(
What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.
Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.
This is your implementation:
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
And this is how you fix your bug:
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>

How to access span tag inside a TD using DOM

How can I access a inside a element on a table and color it?
I tried using childNodes[x] but I'm not sure how to get the span.
<div id="myDiv">
<table>
<tr>
<td>
<span>40 (14)</span>
</td>
</tr>
<tr>
<td>
<span>24 (19)</span>
</td>
</tr>
<tr>
<td>
<span>24</span>
</td>
</tr>
</table>
</div>
(14) should be colored in RED,
(19) should be colored in RED
24 should be unchanged
Check my solution and example running: https://jsfiddle.net/tabvn/bh6y1gc3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<div id="myDiv">
<table>
<tr>
<td>
<span>40 (14)</span>
</td>
</tr>
<tr>
<td>
<span>24 (19)</span>
</td>
</tr>
<tr>
<td>
<span>24</span>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
var nodes = document.querySelectorAll("#myDiv td span");
for(var i = 0; i < nodes.length; ++i){
var node = nodes[i];
var text = node.innerText;
var openIndex = -1;
var closeIndex = -1;
for(var j = 0; j < text.length; ++j){
if(text[j] === "("){
openIndex = j;
}
if(text[j] === ")"){
closeIndex = j;
}
}
var str = "";
if(openIndex > -1 && closeIndex > -1){
for(var j = 0; j < text.length; ++j){
if(j == openIndex){
str += '<span style="color: red;">';
str += text[j];
}else if(j == closeIndex){
str += text[j];
str += "</span>";
}else{
str += text[j];
}
}
node.innerHTML = str;
}
}
</script>
</body>
</html>

Replaces Value in the first row

I really need help in my add to cart function. The problem is that when i added product in the shopping cart the second time, it replaces the value in the first. It should be displayed in another row. Please help me. Thanks.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = "<table border='1|1'>";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
html+="</table>";
document.getElementById("demo2").innerHTML = html;
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
Check below code. I have change it with javascript.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = '';
var ele = document.getElementById("demo2");
if(ele.innerHTML == '')
{
html+="<table id='tblCart' border='1|1'>";
html+="<tr><td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td></tr>";
}
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
if(ele.innerHTML == '')
{
html+= "</table>";
ele.innerHTML = html;
}
else
{
document.getElementById("tblCart").innerHTML += html;
}
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
document.getElementById("demo2").innerHTML = html;
Every time, that function is being called, you are changing the innerHTML of of 'demo2' whereas what you need to do is append to it. Use
document.getElementById("demo2").innerHTML += html;
Also, it is not a good idea to use the innerHTML property.It destroys references thus killing eventListeners or similar stuff linked to the object. Hope it helps !

Error on Javascript code querying SharePoint list

I'm trying to return the contents of a SharePoint list to a HTML page using a JavaScript Query and JSON.
The line:
var query = "**http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title**
does return the DeviceID and Title in browser.
However I don't quite know how I should construct the var query to return results from all the columns. What I've got is:
**var query = " xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";**
I've copied the 'windowsDeviceId' from a previous file which did work. Just having the first var query doesn't return anything and the second returns the attached screen grab. Error code.
The SharePoint columns are: Title, ServiceStatus, Devicetype and DeviceID
JavaScript:
function getDeviceKnownIssues() {
var txtTitle = "";
var txtStatus = "";
//var ServiceStatus = "";
//var Devicetype = "";
//var query = "http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title",
var query = "http://collaboration-xxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = result.DeviceId;
var tempTitle = result.Title;
var StatusType = ServiceStatus;
txtTitle = txtTitle + "<p><a href='/sites/it/SystemInventory/SitePages/Service%20Catalogue.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtStatus = "<p>" + StatusType + "</p>";
});
$('#knowntitle').append($(txtTitle));
$('#servivestatus').append(txtStatus);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
HTML
<html xmlns:mso="urn:schemas-microsoft-com:office:office"
xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<script src="/jquery-1.10.1.min.js"></script>
<script src="/it/SystemInventory/SiteAssets/scripts/moment.min.js"></script>
<script src="/sites/it/SystemInventory/SiteAssets/getDevices.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceDetails.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceKnownIssues.js"></script>
<script type="text/javascript">
function parseQueryString(queryString)
{
var params = {}, queries, temp, i, l;
queries = queryString.split("&");
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
}
$(document).ready(function(){
function getDeviceID() {
if(typeof parseQueryString === "function") {
if(window.location.href.indexOf("?") >= 0) {
var qs = parseQueryString(window.location.href.split("?")[1])
window.DeviceId = qs.did;
getDeviceDetails();
getDeviceKnownIssues();
}
}
}
getDeviceID();
getDevices();
});
</script>
</head>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border- style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Devices</h1>
<div id="devices">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Details</h1>
<div id="devicedetails">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Overview</h1>
<div id="deviceoverview">
<div id="devicekind">
</div>
</td>
</tr>
</table>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Accessories</h1>
<div id="deviceacc">
</div>
</td>
<td class="tg-yw4l">
<h1>Typical Usage</h1>
<div id="deviceuse">
</div>
</td>
<td class="tg-yw4l">
<h1>Spare Cell</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
Known Issues
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Title</h1>
<div id="knowntitle">
</div>
</td>
<td class="tg-yw4l">
<h1>Service Status</h1>
<div id="servivestatus">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Type</h1>
<div id=" ">
</div>
</td>
</tr>
</table>

JavaScript Thumbnails From Array

I'm trying to work on a website currently that displays pictures with the help of java-script. The way that I have this website set up at the moment, an image is displayed above numbered photo links. Instead of having numbers listed below the pictures, I'd like to have the numbers be thumbnails of the pictures. Is it possible to replace them with images? Any help is appreciated.
This is what I have so far:
var photos = new Array();
var photoindex = 0;
photos[0] = "images/piano.jpg";
photos[1] = "images/guitar.jpg";
photos[2] = "images/studio.jpg";
photos[3] = "images/sheetmusic.jpg";
function backward() {
if (photoindex > 0) {
document.images.p.src = photos[--photoindex];
}
}
function forward() {
if (photoindex < photos.length - 1) {
document.images.p.src = photos[++photoindex];
}
}
for (i = 0; i < photos.length; i++) {
document.write("" + i + " ");
}
function goto(n) {
if (n < photos.length && n >= 0) {
photoindex = n;
document.images.p.src = photos[photoindex];
}
}
<br>
<div style="text-align:center;left:5px;">
<table width="250" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" align="center" valign="top">
<img src="images/weloveweb.png" name="p" width="250" height="188" id="p" />
</td>
</tr>
<tr>
<td valign="top"><<
</td>
<td valign="top" style="text-align: center">
</td>
<td valign="top" style="text-align: right">>>
</td>
</tr>
</table>
</div>
Since your thumbnail urls are stored in the photos array, what you need to do to display a thumbnail instead of its index is to create an img tag with a src attribute containing each thumbnail's url (i.e. photos[i]).
Change:
for (i = 0; i < photos.length; i++) {
document.write("" + i + " ");
// ------------------------------------------------------------^ change this `i`
}
Into:
for (i = 0; i < photos.length; i++) {
document.write("" + "<img src=" + photos[i] + "/> ");
}

Categories

Resources