Im developing a prototype mobile web app that mimics a shopping cart. Ive been able to create the shopping cart and add products to the cart. The trouble im having is overwriting the total cost value. Im able to convert the values in order to perform the calculation but im unable to overwrite the value where the total value is stored. Here is the code ive got to far:
<div data-role="content">
<div class="ui-grid-b">
<div class="ui-block-a">Title</div>
<div class="ui-block-b">Format</div>
<div class="ui-block-c">Price</div>
<div class="ui-block-a"><p id = "myTitle"></p></div>
<div class="ui-block-b"><p id = "myFormat"></p></div>
<div class="ui-block-c"><p id = "myPrice"></p></div>
<div class="ui-block-a"></div>
<div class="ui-block-b"></div>
<div class="ui-block-c"><p id="myTotal"></p></div>
</div>
</div>
Now i wish to update the value stored in the "myTotal" id. I have a function called addtocart() and here is the code for that:
`
var total = 0;
function addtocart() {
var title = game.Title ;
var price = game.Price ;
var format = game.Format ;
var newParagraph = document.createElement('p');
newParagraph.textContent = title;
var newParagraph2 = document.createElement('p');
newParagraph2.textContent = format;
var newParagraph3 = document.createElement('p');
newParagraph3.textContent = price;
document.getElementById("myTitle").appendChild(newParagraph);
document.getElementById("myFormat").appendChild(newParagraph2);
document.getElementById("myPrice").appendChild(newParagraph3);
price = parseInt(price, 10);
price = total + price;
var newParagraph4 = document.createElement('p');
newParagraph4.textContent = total;
document.getElementById("myTotal").appendChild(newParagraph4);
}
`
Now i know the appendChild is for adding text to a document but I can seem to find a solution to overwrite the value with the new value stored in 'total' when a new item is added.
Thanks in advance :)
Use the innerHTML property. This will set the HTML inside the element to whatever you set, rather than adding a node.
var newParagraph4 = "<p>" + total + "</p>";
document.getElementById("myTotal").innerHTML = newParagraph4;
This performs less DOM manipulations and is faster than creating the paragraph on the DOM and then adding it.
Change .textContent to innerHTML:
var newParagraph4 = document.createElement('p');
newParagraph4.innerHTML = total;
Related
Java Script
const cardDropdownTemplate = document.querySelector('[Card-Dropdown-Template]');
const cardDropdownContainer = document.querySelector('[card-dropdown-container]');
SearchBoxMainNav.addEventListener('input', async(event) =>{
var input = document.getElementById('SearchTerm').value;
const card = cardDropdownTemplate.content.cloneNode(true).children[0];
cardDropdownContainer.innerHTML = "";
if (input != "") {
var result = cardSearch(input);
console.log(result);
for (var i = 3; i > -1; i--) {
const name = card.querySelector("[Ygo-Card-Name]");
const desc = card.querySelector("[Ygo-Card-Desc]");
name.textContent = result[i].name;
desc.textContent = result[i].desc;
cardDropdownContainer.append(card);
}
console.log(card);
console.log(result);
}
})
Html
<div class="dropdown-Content" card-dropdown-container ></div>
<template Card-Dropdown-Template>
<div class="card-dropdown">
<div class="card-name" Ygo-Card-Name></div>
<div class="card-description" Ygo-Card-Desc></div>
</div>
</template>
So I have this code, when it executes it listens for an input then sends that input into my api searcher, it searches the api for the 4 most simmilar listings in name then Uses a dom template to create a box and puts all the information in it so i can make a Dropdown.
My problem is currently it is only creating one Box and is just overwriting the information in that one box instead of making multiple boxes. Am I just using append wrong or what? When i watch it in slow mo The data gets overwriitten even before the append is reached in the code, so maybe its just drawing the template in real time after the append and the append only makes a new box that first time then does nothing the rest of the times?
I'm making a chat and I want to add an avatar pics feature so I figured it might work well with span, but the problem is I don't know how to add the span to the element.
let avatar = document.createElement("span");
let userMessage = document.createElement("H3");
avatar.setAttribute(userMessage);
userMessage.innerHTML = username + ": " + message;
//document.getElementById("chat").appendChild(avatar);
document.getElementById("chat").appendChild(userMessage);
userMessage.style.background = color;
userMessage.style.textAlign = "left";
document.getElementById("msg").value = "";
I am assuming that you have div with id="chat" and you want to append an h3 tag in a span and then append the chat div so your code will look like this
var username="zulqarnain jalil";
var message ="welcome back, have a nice day";
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
//document.getElementById("msg").value = "";
<div id="chat">
</div>
I have created a chatbot snippet for you, here you can test it
var username="zulqarnain jalil";
function sendMessage()
{
var message =document.getElementById('messagebox').value;
if(message)
{
document.getElementById('messagebox').value='';
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
}
else
{
// message empty
}
}
//document.getElementById("msg").value = "";
<div id="chatBox">
<div id="chat">
</div>
<div>
<input type="text" id="messagebox" />
<input type="button" onclick="sendMessage()" value="Send" />
</div>
</div>
First you need to add the span as a child of the H3 element.
I think the best approach to this problem is creating a class Message. Initializing that class creates h3 and span with unique ids stored in a variable id for future use. The class will also add the h3 as a child of it's parent element ( what ever it is ), and the span as a child of the h3 element.
var counterText = 0;
var counterAvatar = 0;
class UserMessage {
constructor(msgTxt, avatar){
// This block initializes the text message of the user
// It will also add an id to the tag for future use
let msgTxt = document.createTextNode(msgTxt);
this.messageID = 'text' + counterText;
this.message = document.createElement('h3');
this.message.appendChild(msgTxt);
this.message.setAttribute('id', this.messageID);
counterText++;
// This block creates an img element with the attributes src and id
this.avatarID = 'avatar' + counterAvatar;
this.avatar = document.createElement('img');
this.avatar.setAttribute('src', avatar);
this.avatar.setAttribute('id', this.avatarID);
counterAvatar++;
// This block appends the avatar element to the text and the text to the
// chat div.
let chat = document.getElementById('chat');
this.message.appendChild(this.avatar);
chat.appendChild(this.message);
}
}
to initialize a new instance:
var message = new UserMessage("Hello, this is a text message!",'<path/to/avatar>')
this is an object oriented aproach.
you could also just append the avatar to the message and the message to the chat.
But I think aproaching the problem in an object oriented way is much better since it will save time in the future when you're updating your app.
Markdown works fine in here.
Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines.
The begin and end tags of the outermost block element must not be indented.
Markdown can't be used within HTML blocks.
I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop
I need to dynamically insert an element into an existing list of blog posts.
Here is an example of the HTML:
<div id="page">
<div id="post">Post Content</div>
<div id="post">Post Content</div>
<div id="post">Post Content</div>
<div id="post">Post Content</div>
<!---- Dynamic Post Inserted Here--->
<div id="post">Post Content</div>
<div id="post">Post Content</div>
</div>
I've created a for loop that iterates through the posts and returns the location, but the location returned is an integer so I can't append the new post to that variable. So what is the best way to append the item to my current post list?
I don't have the exact function in front of me but this is essentially what i'm doing:
var post = docuemnt.getElementById('post');
var page = docuemnt.getElementById('page');
var pc = 0;
var insert = 5;
var newPost = "new post content";
for(post in page){
if(pc == insert){
**append new post content after this post**
}else{
pc++;
}
}
If you were using jQuery, this would be incredibly easy.
$('#post4').after('<div id="post5">new post content</div>');
If you want to do it in pure JavaScript, then take a look at this question. The basic idea is:
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
In your case, you'd need to create a div node and append to the document directly.
var newpost = document.createElement('div');
newpost.id = 'post5';
newpost.innerText = newpost.textContent = "new post content";
var post = document.getElementById('post4');
post.parentNode.insertBefore(newpost, post.nextSibling);
If you are getting an integer, have the div id be the index. That way you can use document.getElementById('post'+id).innerHTML to append.
Your approach is all wrong, doing a for each on an element won't give you its child nodes but its property keys. You can use getElementsByTagName or querySelector to accomplish your goal
var posts = docuemnt.getElementById('page').getElementsByTagName('div');
var insert = 4;
var newPost = "new post content";
var div = document.createElement('div');
div.appendChild(document.createTextNode(newPost ));
posts[insert].parentNode.insertBefore(div, posts[insert]);//index are zero based so element 4 is actually the 5th element
or
var insert = 5;
var post = docuemnt.querySelector('#page > div:nth-child('+insert+')');//nth child index is one based
var newPost = "new post content";
var div = document.createElement('div');
div.appendChild(document.createTextNode(newPost ));
post.parentNode.insertBefore(div, post);
https://developer.mozilla.org/en-US/docs/DOM/Document.querySelector
https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore
https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByTagName
Your can create jtag for new post div tag and call .dom() function to receive div element. Try Jnerator library.
function addPost() {
var lastPostElement = page.lastChild;
var count = page.childNodes.length;
var postText = tagPost.value;
var jtag = $j.div({ id: 'post' + count, child: postText });
var newPostElement = jtag.dom();
page.insertBefore(newPostElement, lastPostElement);
}
See an example here: http://jsfiddle.net/jnerator/5nCeV/
I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>