Unable to display total using append - javascript

I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}

And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>

Related

How can I assign a javascript variable in html format?

For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)
Open debug console and write there:
lookatthis = 20
But this get you nothing
You can use the log method:
console.log(lookatthis);
Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);
You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');
If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

How do I copy (or even having a button to select it all) a document.getelementbyid output field in html?

I'm trying to essentially set up a button that will either copy a bunch of text that will get output to a document.getelementbyid output to help me out while at work. This is what I have so far for the output and everything works, but would love to have a button that will automatically highlight everything taken from all my input fields.
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + form1 + "<br>form2: " + form2 + "<br>form3: " + form3 + "<br>form4: " + form4 + "<br>form5: " + form5 + "<br>form6: " + form6;
}
This feeds data from my input fields at the top (naturally they have different names and labels in the document, just can't copy anything proprietary here). The below codes are the button code and the paragraph code to display it when I click so that it appears on the page for me to select.
<button onclick="display();" style="width: 50px; background-color:#3ea055">Submit</button>
<p id="output"></p>
I've tried several different snippets of code online to get it to either select or copy or whatever, and it isn't working.
you dont have variables named form1 form2 etc., in the output area I've changed the values to your variable names try this
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn + "<br>form3: " + fan + "<br>form4: " + form4 + "<br>form5: " + requestor + "<br>form6: " + form6;
}
In the line where you print the values to the output element you need to use the variables you just filled.
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn+ "<br>form3: " + fan + "<br>form4: " + business + "<br>form5: " + requestor + "<br>form6: " + reason;

How to setup if-statement with multiple conditions, which uses the valid condition's variable in the if-statement?

Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/

go to the next index of an array using onclick in Javascript

I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)

Categories