http://jsfiddle.net/7118zcfc
$scope.ctx.skills = data.result.skills;
$scope.ThingsYouWouldntLearn = [
"Hooray",
"Amount of mushrooms in Mario.",
"How to complete life.",
"How to create an aryan race",
"How paper papers",
"Do do do dododooooooo",
"A Level Physics / things you dont know = this site",
"How to eat 200000 bananas in .23 seconds",
"Why Jeremy Clarkson has curly hair.",
"Starting to run out of things here",
"Why Oli Stratford looks like James May",
];
$scope.ThingsYouWouldntLearn = $scope.ThingsYouWouldntLearn[Math.floor(Math.random()*$scope.ThingsYouWouldntLearn.length)];
}
How do I make it so when the button that is shown on the jsfiddle is clicked one of these statements is put onto the web page in the same font.
There are a lot of things going on here that you'll need to fix. First, it looks like you're using Angular but its not included on the file. If you were going the Angular route you would have something that looks like:
<!-- HTML -->
<button ng-click="getThingToLearn()" type="button">Learn Something</button>
<p>{{thingToLearn}}</p>
// JS
$scope.thingToLearn = '';
$scope.getThingToLearn = function () {
$scope.thingToLearn = $scope.ThingsYouWouldntLearn[Math.floor(Math.random()*$scope.ThingsYouWouldntLearn.length)];
}
If you're doing more of a JavaScript style then you could do something like:
<!-- HTML -->
<button onclick="getThingToLearn()" type="button">Learn Something</button>
<p id="thingToLearn"></p>
// JS
var getThingToLearn = function () {
var thingToLearn = document.getElementById('thingToLearn');
thingToLearn.textContent = ThingsYouWouldntLearn[Math.floor(Math.random()...
};
Hopefully this will help get you in the right direction to start fixing up your code.
Related
I tried coding a webpage with a functional shopping cart, where you can add items, and see the total money. There's obviously something wrong with my JS, I just don't know what it is since I'm new to JS.
You’re supposed to be able to add items to the cart and see the total amount... I’m unable to add items to cart and see the total. The first function seemed to work but after that none of my JavaScript affected my webpage. I’m assuming I typed something in wrong or I’m missing a few brackets.. etc...
Here's a link to the tutorial I followed
https://www.youtube.com/watch?v=0I1TorcXFP0&list=PLnHJACx3NwAey1IiiYmxFbXxieMYqnBKF&index=5
There is a fair amount of code, I'm just going to put my JS here but the complete code can be found on codepen linked below
https://codepen.io/jlcdevdesign/pen/GRqxBzz
Here's the JS
(function() {
const cartInfo = document.getElementById("cart-info");
const cart = document.getElementById("cart");
cartInfo.addEventListener("click", function() {
cart.classList.toggle("show-cart");
})
})();
(function(){
const cartBtn = document.querySelectorAll(".store-item-icon");
cartBtn.forEach(function(btn){
btn.addEventListener("click", function(event)){
//console.log(event.target);
if(event.target.parentElement.classList("store-item-icon"))
{
let fullPath =
event.target.parentElement.previousElementSibling.src;
let pos = fullPath.indexOf("img") + 3;
let partPath = fullPath.slice(pos);
const item = {};
item.img = 'img-cart${}partPath';
let name = event.target.parentElement.parentElement.nextElementSibling.children[0].children[0].textContent;
item.name = name;
let price = event.target.parentElement.parentElement.nextElementSibling.children[0].children[1].textContent;
let finalPrice = price.slice(1).trim();
item.price = finalPrice;
const cartItem = document.getElementById('div')
cartItem.classList.add('cart-item', 'd-flex', 'justify-content-between', 'text-capitalize', 'my-3');
cartItem.innerHTML = '
<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt="">
<div class="item-text">
<p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p>
<span>$</span>
<span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span>
</div>
<a href="#" id='cart-item-remove' class="cart-item-remove">
<i class="fas fa-trash"></i>
</a>
</div>
';
const cart = deocument.getElementById('cart');
const total = deocument.querySelector('.cart-total-container');
cart.insertBefore(cartItem, total);
alert("item added to the cart");
showTotals();
}
});
})
function showTotals() {
const total = [] {
const items = document.querySelectorAll(".cart-item-price");
items.forEach(function(item){
total.push(parseFloat(item.textContent));
});
}
const totalMoney = total.reduce(function(total,items){
total += item;
return total;
}, 0)
const finalMoney = totalMoney.toFixed(2);
document.getElementById('cart-total').textContent = finalMoney;
document.querySelector('.item-total').textContent = finalMoney;
document.getElementById('item-count').textContent = total.length;
}
})();
In line 53 and 54 you misspelled 'document' with 'deocument' and you also forgot to some braces. And your code is also bit messy, make it harder to read, since you are a beginner this mistakes are common.
Just go through your code carefully correct your spelling and properly put the braces in correct places. And it will solve most of your problems!
I went to your website and found a lot of errors. And your code is also very weird and looks like you just copy pasted and if you really are a begginer or haven't done much projects than you should definetely not do this instead you should try building some simple things like a Rock Paper Scissor game like the one I built when I was a beginner
(simple-rps.vercel.app).
(All the links I have given there are of my old projects you don't have to check them.) And you can press ctrl + u to see the codes then copy the code and paste it into your code editor so that it can get some colours. Then try to read the code and understand how things are working and then try to build your own. And you should not follow that 2 year old tutorial.
Instead you should follow some YouTube channels like Programming with Mosh and Online Tutorials.
HTML:
<div class="container-fluid">
<div class = "row text-center" align = "middle">
<h2>Pseudo Random Quote Machine</h2>
</div>
<div class = "row text-center" align = "middle">
<div class = "col-xs-12 well message" id = "quoting">
</div>
</div>
<div class = "row text-center" align = "middle">
<div class = "col-xs-12">
<button id = "getMessage" class = "btn btn-primary">
Get Random Quote
</button>
<button id = "tweet" class = btn btn-primary>Tweet this!
</button>
</div>
</div>
</div>
Javascript:
function randomQuotes()
{
//array of quotes
var quotes = [ "\"Operator! Give me the number for 911!\" - Homer J. Simpson", "\"I\'m normally not a praying man, but if you\'re up there, please save me Superman\" - Homer J. Simpson", "\"I\'m in no condition to drive...wait! I shouldn\'t listen to myself, I\'m drunk!\" - Homer J. Simpson", "\"A Degenerate, Am I? Well You Are A Festizo. See, I Can Make Up Words Too, Sister\" - Peter Griffen", "\"Victory Shall Be Mine!\" - Stewie Griffen", "\"He's a spy, blow him up. I'm gonna go take a shit.\" - Rick Sanchez", "\"Ohh yea, you gotta get schwifty. \" - Rick Sanchez", "\"Yo! What up my glip glops!\" - Rick Sanchez", "\"WUBBA LUBBA DUB DUBS!!! \" - Rick Sanchez", "\"Existence is pain to a meeseeks Jerry, and we will do anything to alleviate that pain.\" - Mr. Meeseeks", " \"It\'s morphine time\" - TheRussianBadger"];
var randNum = Math.floor((Math.random() * quotes.length));
document.getElementById("quoting").innerHTML = quotes[randNum];
}
function tweetThis()
{
var tweetToShare = document.getElementById("quoting").innerHTML;
var tweetUrl = 'https://twitter.com/share?text=' + encodeURIComponent(tweetToShare) + ".";
window.open(tweetUrl);
}
document.getElementById("getMessage").onclick = function(){randomQuotes();}
document.getElementById("tweet").onclick = function(){tweetThis();}
Basically, any time I click either of the two buttons the function keeps being called over and over again. Here is the code running in Code Pen
I guess my questions would be:
why would the functions be called more than one time ?
What should I do to either stop the functions from being called multiple times or prevent it from happening in the first place?
functions seem to be called only one time on chrome. Maybe your browser cached an old script: maiusc+f5 to clean
Pastebin of index.html: http://pastebin.com/kdKFqTxe
Just copy and paste that and run it (this works but with some broken img links & no css).
With regards to the pastebin, just click on a node, and then click the first broken image below the video. What should happen is a dialogue box should appear with links to articles (from tubeArray). All relevant code is pasted below.
I'm trying to dynamically change the contents of a div when I click an image. The image has it's respective id (the first index in the inner array) within the first inner array there's another array (index 3). I want to populate my div (id="articleLinks") with those links using JQuery when the image is clicked.
JavaScript & JQuery:
The tube array. *Note: the first index of each element in tubeArray is the ID & the news articles aren't linked to anything particular. Only interested in tubeArray[0] & tubeArray[4]
var tubeArray = [
['UQ', -27.495134, 153.013502, "http://www.youtube.com/embed/uZ2SWWDt8Wg",
[
["example.com", "Brisbane students protest university fee hikes"],
["example.com", "Angry protests over UQ student union election"],
]
],
['New York', 40.715520, -74.002036, "http://www.youtube.com/embed/JG0wmXyi-Mw",
[
["example.com" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]
]
],
['To The Skies', 47.09399, 15.40548, "http://www.youtube.com/embed/tfEjTgUmeWw",
[
["example.com","Battle for Kobane intensifies as Islamic State uses car bombs, Syrian fighters execute captives"],
["example.com","Jihadists take heavy losses in battle for Syria's Kobane"]
]
],
['Fallujah', 33.101509, 44.047308, "http://www.youtube.com/embed/V2EOMzZsTrE",
[
["example.com","Video captures family cat saving California boy from dog attack"],
["example.com","Fines of £20,000 for dogs that chase the postman"]
]
]
];
A for loop which goes through each element in tubeArray then assigns id to the first index. Also an image that calls the function myFunctionId which takes the parameter this.id.
for (i = 0; i < tubeArray.length; i++) {
var id = tubeArray[i][0];
//other code
'<img src="img.png" onclick="myFunctionId(this.id);" id="' + id + '">' +
//other code
}
function myFunctionId (id) {
journal = id;
alert(journal) //just a test
//I want to search through tubeArray with the id and find the matching inner array.
//I then want to loop through the innerArray and append to my html a link using JQuery.
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
}
}
HTML:
<div id="articleLinks">
Example Link<br>
</div>
Any help would be greatly appreciated. I've tried to simplify & cut out as much as I can so it's readable.
try this...
function myFunctionId (id) {
console.log(tubeArray);
tubeArray.forEach(function(entry) {
if (entry[0]==id) {
entry[4].forEach(function(innerArray){
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
});
return;
}
});
}
it makes it look like this for me... you're gonna have to handle that encoding issue. with the apostrophe. there are a lot of ways to handle it...
so.... if it was me... which it's not. but if it was... i would use an associative array instead of a numerically indexed one because it's easier to read the code and understand what you're using and where and how and things and stuff.
tubeArray = {
'UQ' : { 'location': [-27.495134, 153.013502],
'youtube': "example.com/embed/uZ2SWWDt8Wg",
'articles': [["example.com/queensland/brisbane-students-protest-university-fee-hikes-20140521-zrk8o.html", "Brisbane students protest university fee hikes"],
["example.com/content/2012/s3578878.htm", "Angry protests over UQ student union election"], ]
},
'New York': { 'location': [0.715520, -74.002036],
'youtube': "example.com/embed/JG0wmXyi-Mw",
'articles': [["example.com/2014/10/19/ny-taxpayers-risky-wall-street-bet-why-the-comptroller-race-matters/" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]],
},
}
Problem Overview
Let's say I have a shipment of candy. The shipment has a number of boxes, and each box has a number of unique candy types. Every box has a unique id, different from every other box; the same is true for candy types. Furthermore, a candy has additional traits, like color, flavor and quantity.
Example Code
Take the following HTML example:
<div class="shipment">
<div class="box" data-boxid="a">
<div class="candy" data-candyid="1" data-color="orange" data-flavor="orange" data-qty="7">
<!-- unimportant content -->
</div>
<div class="candy" data-candyid="2" data-color="red" data-flavor="strawberry" data-qty="4">
<!-- unimportant content -->
</div>
</div>
<div class="box" data-boxid="b">
<div class="candy" data-candyid="3" data-color="green" data-flavor="lime">
<!-- unimportant content -->
</div>
</div>
</div>
Previous Attempts
I've seen similar examples of table parsing with jQuery's .map() function, and I've also seen mention of .each(), but I've been unable to generate any working code.
Desired Output
I want to generate (with jQuery) a JSON object similar to the following:
{
"shipment": {
"a": {
"1": {
"color": "orange",
"flavor": "orange",
"qty": "7"
},
"2": {
"color": "red",
"flavor": "strawberry",
"qty": "4"
}
},
"b": {
"3": {
"color": "green",
"flavor": "lime"
}
}
}
}
Additional Notes
My app already uses jQuery extensively, so it seems like a logical tool for the job. However, if plain 'ol JavaScript is a more appropriate choice, feel free to say so.
The HTML is always going to be well-formed and always going to follow a the format specified. However, in some cases, information may be incomplete. Note that the third candy had no quantity specified, so quantity was simply ignored while building the object.
This generates what you asked for:
var json = {};
$('.shipment').each(function(i,a) {
json.shipment = {};
$(a).find('.box').each(function(j,b) {
var boxid = $(b).data('boxid');
json.shipment[boxid] = {};
$(b).find('.candy').each(function(k,c) {
var $c = $(c),
candyid = $c.data('candyid'),
color = $c.data('color'),
flavor = $c.data('flavor'),
qty = $c.data('qty');
json.shipment[boxid][candyid] = {};
if (color) json.shipment[boxid][candyid].color = color;
if (flavor) json.shipment[boxid][candyid].flavor = flavor;
if (qty) json.shipment[boxid][candyid].qty = qty;
});
});
});
http://jsfiddle.net/mblase75/D22mD/
As you can see, at each level it uses .each() to loop through the elements matching a certain class and then .find().each() to loop through the desired children. In between, .data() is used to grab the desired data- attributes and the json object is built level by level.
Is this close to what you are looking for? – http://jsfiddle.net/4RPHL/
I have used data() and JSON.stringify to create the json.
Be sure to check your console where I have logged the output.
$(".candy").each(function() {
console.log(JSON.stringify($(this).data()))
});
Nice problem! Thanks to Chris' post I was able to get this to work.
var shipments = [],
shipment = {},
boxes = {},
candy = {};
$(".shipment").each(function() {
var shipment = {},
boxes = {};
$(this).children().each(function(){
var boxdata = $(this).data();
candy = {};
$(this).children().each(function(){
var candydata = $(this).data();
candy[candydata["candyid"]] = {
color: candydata["color"],
flavor: candydata["flavor"],
qty: candydata["qty"]
};
boxes[boxdata["boxid"]] = candy;
});
//console.log(JSON.stringify(boxes)); // works
});
shipment = {shipment: boxes};
shipments.push(shipment); // for multiples
});
console.log(JSON.stringify(shipments[0]));
console.log(shipments.length); // 1 for the example html above
EDIT: Would the approach be much easier if the Javascript listed was removed completely, and the dropdown menus restyled as <div>'s within <li>'s, and the final div was generated by a Javascript onclick event? e.g.
<a id="click_link">click me</a>
$("#click_link").click(function(){
$('#div').load('http://www.link.com/');
});
Either way, the problem at hand...
My decision to use an elegant-looking javascript solution is highlighting my massive inexperience when it comes to javascript! The problem is, on the face of it, simple...
Once an option has been chosen on each of the dropdown menus, I need a final div to load so that a specific button can be shown (a link to buy the item with the specified options, e.g. choosing Necklace D, with Stone Option B, and Delivery Option A = loading div with 'Buy' Button #17)
The dropdowns are divs that are filled and styled through the Javascript (as opposed to using the simpler <form> and <input> method), giving the flexibility to add two lines of differently styled text for each option etc. - This is where I step into the realm of the unknown and my inexperience shines through.
The isolated section is viewable in its entirity here
Ok, to the code.
Here's the Javascript:
function createByJson() {
var pearlData = [
{description:'Choose your pearl...', value:'Pearls', text:'Pearls'},
{description:'Beautiful black stone', value:'Black Pearl', text:'Black Pearl'},
{description:'Classic white stone', value:'White Pearl', text:'White Pearl'}
];
$("#DropItPearls").msDropDown({byJson:{data:pearlData, name:'pearls', width: 200}}).data("dd");
var blodeuweddData = [
{description:'Choose your item...', value:'Blodeuwedd', text:'the Blodeuwedd Collection'},
{description:'A striking statement', value:'BlodeuweddCelticStatement', text:'Celtic Statement Piece'},
{description:'Gold laced flower and pearl', value:'BlodeuweddBracelet', text:'Bracelet'},
];
$("#DropItBlodeuwedd").msDropDown({byJson:{data:blodeuweddData, name:'blodeuwedd', width: 250}})
.msDropDown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var deliveryData = [
{description:'Choose your method...', value:'Delivery', text:'Delivery Options'},
{description:'4-6 weeks delivery', value:'Four Weeks', text:'Made To Order'},
{description:'(unavailable on this item)', value:'Rush', text:'Express Delivery', disabled:true}
];
$("#DropItDelivery").msDropDown({byJson:{data:deliveryData, name:'delivery', width: 200, selectedIndex: 1}}).data("dd");
paymentData = [
{ description:'How would you like to pay?', value:'Payment', text:'Payment Method'},
{image:'images/msdropdown/icons/Visa-56.png', description:'Secure online payment', value:'Visa', text:'Visa'},
{image:'images/msdropdown/icons/Paypal-56.png', description:'Secure online payment', value:'Paypal', text:'Paypal'},
{image:'images/msdropdown/icons/EmailPay-56.png', description:'Order by email', value:'Email Payment', text:'Send Your Details'},
{image:'images/msdropdown/icons/Mastercard-56.png', description:'(coming soon)', value:'Mastercard', text:'Mastercard', disabled:true},
{image:'images/msdropdown/icons/Collect-56.png', description:'(coming soon)', value:'Collection', text:'Order and Collect', disabled:true},
{image:'images/msdropdown/icons/Email-56.png', description:'email Menna', value:'Other Method', text:'Alternatives'}
];
$("#DropItPayments").msDropDown({byJson:{data:paymentData, name:'payments', width: 250}}).data("dd");
}
$(document).ready(function(e) {
//no use
try {
var pages = $("#pages").msDropdown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var pagename = document.location.pathname.toString();
pagename = pagename.split("/");
pages.setIndexByValue(pagename[pagename.length-1]);
$("#ver").html(msBeautify.version.msDropdown);
} catch(e) {
//console.log(e);
}
$("#ver").html(msBeautify.version.msDropdown);
//convert
$("select").msDropdown();
createByJson();
$("#tech").data("dd");
});
function showValue(h) {
console.log(h.name, h.value);
}
$("#tech").change(function() {
console.log("by jquery: ", this.value);
})
//
And the html:
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Item</p></div>
<div id="DropItBlodeuwedd"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Precious Stones</p></div>
<div id="DropItPearls"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Payment</p></div>
<div id="DropItPayments"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Delivery</p></div>
<div id="DropItDelivery"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Buy Now!</p></div>
<div id="DropItBuy"></div>
</div>
Again, working version viewable here
Many thanks in advance!
What I think you want is for your Buy button to dynamically read what the dropdowns currently say and build a link for redirection based on that, rather than trying to update the Buy button every time a dropdown changes.
From your code I can't see what the form of the final URL is supposed to be. For example, to get the current value of the delivery option, you can check $('#DropItDelivery :selected').text() which will be something like "Made To Order".
Your Buy Now! could be a button with a click event that reads these values and constructs the URL with basic string concatenation, e.g.:
window.location = "buynow.html?delivery=" + $('#DropItDelivery :selected').text() +
"&payment=" + $('#DropItPayments :selected').text()
// etc.
Of course you'd have to handle these options on the server.
In case you want to redirect to the payment page of the processor, you can just branch based on the payment method and give them the URL you want based on that.
var pm = $('#DropItPayments :selected').text();
if (pm == "Visa")
{
// Visa payment URL construction
}
else if (pm == "Send Your Details")
{
// Send your details URL construction
}
// etc.