<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quote generator</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1 class = "quotes">Quotes</h1>
<img src ="https://placeimg.com/1100/300/nature" alt="nature" class="nature">
<div id = "output">
</div>
<script type ="text/javascript" src="js/student_report.js"></script>
<button onclick="print(blank)">Click me</button>
</body>
</html
> Blockquote
function print(message) { var output =
document.getElementById('output'); output.innerHTML = message; }
Blockquote
var blank = "";
function print(message) {
var output = document.getElementById('output');
output.innerHTML = message;
}
function getQuote(array) {
var quotes = '<h2 class="quote">' + 'quote: ' + array.quote + '</h2>';
quotes += '<p class="source">' + 'Soure: ' + array.source + '</p>';
quotes += '<p class="year">' + 'year: ' + array.year + '</p>';
quotes += '<p class="citation">' + 'citation: ' + array.citation + '</p>';
return quotes
};
>
var quotes = [{
quote: "Great man", source: "jack mike", year: 1990, citation: "movie"},
{ quote: "Good stuff", source:"Mac jones", year: 1989, citation: "book"},
{ quote: "i love you", source: "mom and dad", year: 1993, citation: "love"},
{quote: "you're a hero", source: "hero man", year: 2020, citation: "future"},
{quote: "you're a wizard", source: "hero wizard", year: 2022, citation: "future4"},
{quote: "you're a man", source: "hero man33", year: 2025, citation: "future3"},
{quote: "you're a good person", source: "hero person", year: 2021, citation: "future2"},
{quote: "you're a web developer", source: "hero developer", year: 2026, citation: "futures"}
];
var i = Math.round(Math.random() * quotes.length - 1);
blank += getQuote(quotes[i]);
print(blank);
function timer(){
setInterval(print(blank), 3000);
}
timer();
So here I need to link that print function to the onclick so that when I click the button, it keeps printing out that message to the page in the same spot. It's a random quote generator code so what I want is it prints random quotes to the page when i click the button.
When I load the page everything loads as it should, but when I click the button NOTHING happens, just clicks and that's it.
IGNORE THE QUOTES TEXT its stupid dumb stuff long story, i would never use those quotes for a actual website
Sorry if I gave a bad description, as you can see I'm new to coding.
Thank you for the help!
The problem is when you're calling your function from the onclick attribute here:
<button onclick="print(blank)">Click me</button>
You would have seen an error in the JavaScript console saying this when you clicked the button:
ReferenceError: Can't find variable: blank
If you want to print blank, you'll need quotation marks around the string you want to print. You can either use single quotation marks like so:
<button onclick="print('blank')">Click me</button>
Or you can use escaped double quotes like this:
<button onclick="print(\"blank\")">Click me</button>
Is the print() function defined in the student_report.js file? If not, you have to also define the function in a <script> tag. And like said already, the "blank" variable has to be in a global scope.
The argument in the javascript file is called blank
Not sure what you mean there. If you're trying to pass a variable, it would have to be in global scope
Edit:
ok, it looks like the problem is that you're expecting print(blank) to change the quote displayed in the output div but print only changes the innerHTML of the div, it doesn't change blank, here's your code with a console.log in print to show that print is called.
var blank = "";
function print(message) {
console.log('here')
var output = document.getElementById('output');
output.innerHTML = message;
}
function getQoute(array) {
var qoutes = '<h2 class="qoute">' + 'qoute: ' + array.qoute + '</h2>';
qoutes += '<p class="source">' + 'Soure: ' + array.source + '</p>';
qoutes += '<p class="year">' + 'year: ' + array.year + '</p>';
qoutes += '<p class="citation">' + 'citation: ' + array.citation + '</p>';
return qoutes
};
var qoutes = [{
qoute: "Great man", source: "jack mike", year: 1990, citation: "movie"},
{ qoute: "Good stuff", source:"Mac jones", year: 1989, citation: "book"},
{ qoute: "i love you", source: "mom and dad", year: 1993, citation: "love"},
{qoute: "you're a hero", source: "hero man", year: 2020, citation: "future"},
{qoute: "you're a wizard", source: "hero wizard", year: 2022, citation: "future4"},
{qoute: "you're a man", source: "hero man33", year: 2025, citation: "future3"},
{qoute: "you're a good person", source: "hero person", year: 2021, citation: "future2"},
{qoute: "you're a web developer", source: "hero developer", year: 2026, citation: "futures"}
];
var i = Math.round(Math.random() * qoutes.length - 1);
blank += getQoute(qoutes[i]);
print(blank);
function timer(){
setInterval(print(blank), 3000);
}
timer();
<h1 class = "qoutes">Qoutes</h1>
<img src ="https://placeimg.com/1100/300/nature" alt="nature" class="nature">
<div id = "output">
</div>
<script type ="text/javascript" src="js/student_report.js"></script>
<button onclick="print(blank)">Click me</button>
Here's an update to your code that updates the quote and fixes a bunch of other stuff:
const quotes = [
{ quote: "Great man", source: "jack mike", year: 1990, citation: "movie" },
{ quote: "Good stuff", source:"Mac jones", year: 1989, citation: "book" },
{ quote: "i love you", source: "mom and dad", year: 1993, citation: "love" },
{ quote: "you're a hero", source: "hero man", year: 2020, citation: "future" },
{ quote: "you're a wizard", source: "hero wizard", year: 2022, citation: "future4" },
{ quote: "you're a man", source: "hero man33", year: 2025, citation: "future3" },
{ quote: "you're a good person", source: "hero person", year: 2021, citation: "future2" },
{ quote: "you're a web developer", source: "hero developer", year: 2026, citation: "futures" }
];
function changeQuote() {
const i = Math.floor(Math.random() * quotes.length);
document.getElementById('output').innerHTML = getQuote(quotes[i]);
}
function getQuote({quote, source, year, citation}) {
return `
<h2 class="quote">quote: ${quote}</h2>
<p class="source">soure: ${source}</p>
<p class="year">year: ${year}</p>
<p class="citation">citation: ${citation}</p>`;
};
changeQuote();
<h1 class = "quotes">Quotes</h1>
<img src ="https://placeimg.com/1100/300/nature" alt="nature" class="nature">
<div id = "output">
</div>
<script type ="text/javascript" src="js/student_report.js"></script>
<button onclick="changeQuote()">Click me</button>
replace below code instead of your existing button code
<button onclick="print('blank')">Click me</button>
when you send string to a function you have to use single/double quotes otherwise it will consider as js variable.
Related
Hey guys I'm currently working on a JSDares challenge that I just can't seem to wrap my head around.
Here's the link, it's called "More Information":
https://jsdares.com/?dare=300000000000000000000109
Here is the code I currently have:
function person(name, born, died, knownFor) {
if(died == 0) {
console.log("Name : " + name);
console.log("Born in : " + born);
console.log("Known for : " + knownFor);
console.log("");
} else {
console.log("Name : " + name);
console.log("Born in : " + born);
console.log("Died in : " + died);
console.log("Known for : " + knownFor);
console.log("");
}
}
console.log("Famous people in computing:");
console.log("");
person("Charles Babbage", 1815, 1871, "first computer");
person("Ada Lovelace", 1815, 1852, "first programmer");
person("George Boole", 1815, 1864, "Boolean logic");
person("Grace Hopper", 1906, 1992, "first language");
person("Alan Turing", 1912, 1954, "Turing machine");
person("Douglas Engelbart", 1925, 0, "Computer mouse");
person("Bill Gates", 1955, 0, "Microsoft");
person("Steve Jobs", 1955, 2011, "Apple");
person("Linus Torvalds", 1969, 0, "Linux");
person("Tim Berners-Lee", 1955, 0, "World Wide Web");
console.log("And many more...");
What I can't seem to figure out is how to reduce the amount of lines I'm using. When I use an IF statement, inside the function, I end up writing a CONSOLE.LOG for every PARAMETER and I can't seem to find an operator or method that will exclude the "DIED" parameter in the ELSE part of the statement. Any tips?
You don't need to use your if statement for the entire function, but only for one line. I've fix your code in the example below, and also tested it on your submission website:
function person(name, born, died, knownFor) {
console.log("Name : " + name);
console.log("Born in : " + born);
if (died != 0) {
console.log("Died in : " + died);
}
console.log("Known for : " + knownFor);
console.log("");
}
console.log("Famous people in computing:");
console.log("");
person("Charles Babbage", 1815, 1871, "first computer");
person("Ada Lovelace", 1815, 1852, "first programmer");
person("George Boole", 1815, 1864, "Boolean logic");
person("Grace Hopper", 1906, 1992, "first language");
person("Alan Turing", 1912, 1954, "Turing machine");
person("Douglas Engelbart", 1925, 0, "Computer mouse");
person("Bill Gates", 1955, 0, "Microsoft");
person("Steve Jobs", 1955, 2011, "Apple");
person("Linus Torvalds", 1969, 0, "Linux");
person("Tim Berners-Lee", 1955, 0, "World Wide Web");
console.log("And many more...");
I am trying to web scrape product reviews from a page but I'm not sure how to extract a var inside the <script> tags.
Here's my python code:
import requests
from bs4 import BeautifulSoup
import csv
a_file = open("ProductReviews.csv", "a")
writer = csv.writer(a_file)
# Write the titles of the columns to the CSV file
writer.writerow(["created_at", "reviewer_name", "rating", "content", "source"])
url = 'https://www.lazada.com.my/products/iron-gym-total-upper-body-workout-bar-i467342383.html'
# Connect to the URL
response = requests.get(url)
# Parse HTML and save to BeautifulSoup object
soup = BeautifulSoup(response.content, "html.parser")
data = soup.findAll('script')[123]
if 'var __moduleData__' in data.string:
print("Yes")
Here's the page source (I removed the unnecessary code):
<html>
<head>
<title></title>
</head>
<body>
<script>
var __moduleData__ = {
"data": {
"root": {
"fields": {
"review": {
"reviews": [{
"rating": 5,
"reviewContent": "tq barang dah sampai",
"reviewTime": "24 May 2021",
"reviewer": "Jaharinbaharin",
}, {
"rating": 5,
"reviewContent": "Beautiful quality๐๐๐",
"reviewTime": "08 Sep 2021",
"reviewer": "M***.",
}, {
"rating": 5,
"reviewContent": "the box was badly dented but the item was intact...just that my door frame is shallow and slippery....I can't pull up without worrying of falling down",
"reviewTime": "25 Aug 2021",
"reviewer": "David S.",
}, {
"rating": 5,
"reviewContent": "Havenโt really opened it yet but please put some effort on the packaging for future improvement thanks it was really fast",
"reviewTime": "14 Dec 2020",
"reviewer": "Yasir A.",
}, {
"rating": 5,
"reviewContent": "Seems to be ok, good quality.. No weight restriction mentioned on the box.. I'm about 90kg, it could handle my weight so far..",
"reviewTime": "22 May 2020",
"reviewer": "Kevin",
}]
},
}
},
},
};
</script>
</body>
</html>
I just want to get the review data only so I'd like to know how to extract the value of var __moduleData__.
You can use a regex to select your variable:
json.loads(re.search(r'var __moduleData__ = ({.*})', response.text).group(1))
Example
from bs4 import BeautifulSoup
import json,re,requests
url = 'https://www.lazada.com.my/products/iron-gym-total-upper-body-workout-bar-i467342383.html'
response = requests.get(url)
d = json.loads(re.search(r'var __moduleData__ = ({.*})', response.text).group(1))
d['data']['root']['fields']['seller']
Output
{'chatResponsiveRate': {'labelText': 'Chat Response', 'value': '100%'},
'chatUrl': 'https://pages.lazada.com.my/wow/i/my/im/chat?brandId=21411',
'hideAllMetrics': False,
'imEnable': True,
'imUserId': '100285367',
'name': 'MR SIX PACK',
'newSeller': False,
'percentRate': '96%',
'positiveSellerRating': {'labelText': 'Seller Ratings', 'value': '96%'},
'rate': 0.96,
'rateLevel': 3,
'sellerId': '1000052649',
'shipOnTime': {'labelText': 'Ship On Time', 'value': '97%'},
'shopId': 255007,
'size': 5,
'time': 2,
'type': '4',
'unit': 'years',
'url': '//www.lazada.com.my/shop/mr-six-pack/?itemId=467342383&channelSource=pdp'}
In my program, I make a call to my python script to return a dictionary. I am trying to access this dictionary in JavaScript after completing the XMLHttpRequest. response text. The dictionary will appear however, I am not able to parse it.
For example: calling this,responseText['Username']; returns undefined
I have tried stringifying the responseText and then parsing it, which hasn't helped at all. What am I doing wrong? I have been stuck on this for too long
Requested function:
def getBasicInfo():
dict = {}
list = []
username = ud["username"]
displayName = ide["displayName"]
accountCreationDate = ud['creationTime']
following = fol["followingUsersCount"]
followers = fol['followerCount']
playlistCount = len(ply["playlists"])
playlists = ply["playlists"]
dict.update({"Username": username})
dict.update({"Display Name": displayName})
dict.update({"Account Creation Date": accountCreationDate})
dict.update({"Following": str(following)})
dict.update({"Followers": str(followers)})
dict.update({"Number of playlists": str(playlistCount)})
for x in range(0, len(ply["playlists"])):
list.append(playlists[x]["name"])
dict.update({"Playlist names": list})
totalNumberSongs = len(sh1) + len(sh2) + len(sh3)
firstTime = sh1[0]['endTime']
lastTime = sh3[-1]['endTime']
dict.update({"Total Number of Songs Analyzed": str(totalNumberSongs)})
timeStamp = firstTime + " to " + lastTime
dict.update({"Data Lifecycle": timeStamp})
return dict
Python Script:
#!\Users\bobs\anaconda3\python.exe #Python Interpreter
from data import *
import cgi
import sys
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
if "basic" in fs.keys():
info = getBasicInfo()
print(info)
if "artist" in fs.keys():
artist = countArtistsDesc()
print(artist)
if "song" in fs.keys():
song = countSongsDesc()
print(song)
if "day" in fs.keys():
day = getHighestPlayedDays(True)
print(day)
if "playlist" in fs.keys():
playlist = getPlaylist()
print(playlist)
sys.stdout.write("\n")
sys.stdout.close()
HTML Page/XMLHTTPRequest:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basic Info</title>
</head>
<body style="background-color:#1DB954">
<h1 align="center">User's Basic Info</h1>
<script>
var http = new XMLHttpRequest();
http.open('GET', '/cgi-bin/simpleData.py?basic=True', true);
http.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
// http.responseType = 'json'
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("responseText").innerHTML = this.responseText;
document.getElementById("problem").innerHTML = this.responseText['Username'];
}
};
http.send(null);
</script>
<p id="responseText"></p>
<p id="problem"></p>
</body>
</html>
Output:
{'Username': 'bobsmith123', 'Display Name': 'Bob Smith', 'Account Creation Date': '2016-10-10', 'Following': '34', 'Followers': '46', 'Number of playlists': '32', 'Playlist names': ['5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party ๐ป', 'Rap', 'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies', 'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020', 'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour', 'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP", 'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld ๐ข๐ก๐ ', 'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'], 'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'}
undefined
Solution:
#Very end of getBasicInfo()
return json.dumps(dict, separators=(',', ':'))
#After readyState == 4 && this.status == 200 in the HTML page
parsed = JSON.parse(this.responseText);
This is because python represents strings with single quotes, and json requires double quotes.
import json;
body = {'Username': 'bobsmith123', 'Display Name': 'Bob Smith',
'Account Creation Date': '2016-10-10', 'Following': '34',
'Followers': '46', 'Number of playlists': '32',
'Playlist names': [
'5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party ๐ป', 'Rap',
'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies',
'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020',
'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour',
'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP",
'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld ๐ข๐ก๐ ',
'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'],
'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'
}
print(json.dumps(body))
That produces the output in the correct format
{"Username": "bobsmith123", "Display Name": "Bob Smith", "Account Creation Date": "2016-10-10", "Following": "34", "Followers": "46", "Number of playlists": "32", "Playlist names": ["5th Dimension", "Dumb Chilling", "Rock v2 / Nu Metal", "Party \ud83c\udf7b", "Rap", "Pumping Iron", "Aggression", "Soundcloud 4", "Oldies but Goodies", "Chopped and Screwed", "Cruel Winter", "Soundcloud", "Halloween 2020", "Trap Christmas", "80's Night", "EDM", "Life of Pablo Tour", "Igor Tour", "Thugger", "Playboi Carti", "Cactus Jack", "WAKE UP MR WEST, OH HE'S UP", "Future", "Denzel", "LORDE PRETTY FLACKO JOYDE", "AstroWorld \ud83c\udfa2\ud83c\udfa1\ud83c\udfa0", "Daytona Tour", "Children of the Korn", "Rock", "Classics", "Floyd", "Chill Rock"], "Total Number of Songs Analyzed": "27334", "Data Lifecycle": "2020-01-24 19:37 to 2021-01-25 20:52"}
and as a bonus you get escaped unicode characters.
So I'm creating a view that shows a list of ads. Each ad is an object in an array and has properties (title, description, dates, etc.) I wrote the javascript to display them in order and created a drop down list of title, description, date, etc. and need to sort the ads according to the selected property in the drop down list. I have a function that sorts the objects by property, and I want to have eventlisteners on each option selected, but then I'm not sure how to implement this since I'm using a loop to display all the ad objects.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="sortList">
<select id="selectSort" onchange="myFunction()">
<option value="value1">value1
<option value="value2">value2
<option value="value3">value3
</select>
</div>
<div id="container"></div>
</body>
</html>
Script
var array = [
{
value1: "this is an attribute", value2: "this is the second attribute", value3: "this is the 3rd attribute"
},
{
value1: "this is an attribute of 2nd object", value2: "this is the second attribute of 2nd object", value3: "this is the 3rd attribute of 2nd object"
},
{
value1: "this is an attribute of 2nd object", value2: "this is the second attribute of 2nd object", value3: "this is the 3rd attribute of 2nd object"
},
];
const container = document.getElementById("container");
for( { value1, value2, value3 } of array) {
const wrapper = document.createElement("div");
wrapper.className = "wrapper";
const first= document.createElement("h1");
first.textContent = value1;
const second= document.createElement("p");
second.textContent = value2;
const third= document.createElement("sub");
third.textContent = value3;
// append
wrapper.appendChild(first);
wrapper.appendChild(second);
wrapper.appendChild(third);
container.appendChild(wrapper);
}
//function that sorts ads by properties
function sortBy(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
//I want to have eventlisteners on each option selected but then not sure how to implement this since I'm using a loop to display all the ads
array.sort(sortBy("value1"));
You can try like this way to add an eventlistener on your select element and then grab the selected value on your myFunction(). But before that you've modify your option values first, like this to easily get and use it on your sorting function.
<select id="selectSort" onchange="myFunction(this.value)">
<option value="title">Title</option>
<option value="description">Description</option>
<option value="start_date">Start date</option>
<option value="end_date">End date</option>
<option value="offer">Most products</option>
<option value="num_of_products">Least products</option>
</select>
Also initialize the content of container.innerHTML = ''; it'll help you to refresh your div after changing the sort order. I've also wrap it bodyContent() function for the code re-usability. Hope this helps :) See your pen here again
var ads = [{
title: "Photo Play Paper Collections",
description: "Don't miss these brand new Photo Play Paper Collections!",
start_date: "2018-09-01",
end_date: "2018-12-30",
offer: "50% Off",
num_of_products: 7
},
{
title: "Foil & Foiling Accessories",
description: "Once you add this color & shine to your paper, wood, fabric, or other porous surfaces you'll want to do it over and over again.",
start_date: "2018-08-01",
end_date: "2018-11-30",
offer: "Save $25",
num_of_products: 10
},
{
title: "The Halloween Shop",
description: "Shop all our spooky supplies in one place!",
start_date: "2018-09-01",
end_date: "2018-10-30",
offer: "35% Off",
num_of_products: 8
},
{
title: "Waffle Flower Crafts Stamps & Dies",
description: "We can't stop talking about these new Waffle Flower Stamps and Dies!",
start_date: "2018-09-01",
end_date: "2018-09-30",
offer: "Save $30",
num_of_products: 19
},
{
title: "Die Cutting & Embossing",
description: "Save on Die Cutting and Embossing Folders at Blitsy! Shop hundreds of amazing Dies and Embossing Folders from brilliant designers at Sizzix, Spellbinders, and CottageCutz (to name a few!)",
start_date: "2018-08-01",
end_date: "2018-12-30",
offer: "Save $50",
num_of_products: 23
},
{
title: "American Crafts Tools, Paper Collections & More",
description: "American Crafts prides themselves on innovation with their scrapbooking products. You can find crafting embellishments, stickers, and more.",
start_date: "2018-08-01",
end_date: "2018-11-30",
offer: "45% Off",
num_of_products: 35
},
{
title: "The Fall Shop!",
description: "The Fall Shop has everything you need for the upcoming season!",
start_date: "2018-09-01",
end_date: "2018-09-30",
offer: "60% Off",
num_of_products: 50
},
{
title: "Moxy Glitter, Embossing Powers, & More!",
description: "Eye catching glitters from this new brand by American Crafts!",
start_date: "2018-09-01",
end_date: "2018-09-30",
offer: "10% Off",
num_of_products: 24
},
{
title: "Brutus Monroe Stamps, Dies, Tools & More",
description: "On Sale Now! New Arrivals from Brutus Monroe",
start_date: "2018-08-01",
end_date: "2018-10-30",
offer: "Save $75",
num_of_products: 10
},
{
title: "Fiskars Tools & Accessories",
description: "Shop All the New Tools & Accessories that will make your life easier.",
start_date: "2018-08-01",
end_date: "2018-09-30",
offer: "15% Off",
num_of_products: 5
},
];
function bodyContent() {
const container = document.getElementById("container");
container.innerHTML = '';
for ({
title,
description,
start_date,
end_date,
offer,
num_of_products
} of ads) {
const wrapper = document.createElement("div");
wrapper.className = "wrapper";
const headline = document.createElement("h1");
headline.textContent = title;
const descrip = document.createElement("p");
descrip.textContent = description;
const dates = document.createElement("sub");
dates.textContent = "Offer valid " + start_date + " through " + end_date;
const discount = document.createElement("h2");
discount.textContent = offer;
const products = document.createElement("h4");
products.innerHTML = num_of_products + " items still available! <a href=#>Shop Now</a>";
// append
wrapper.appendChild(headline);
wrapper.appendChild(discount);
wrapper.appendChild(descrip);
wrapper.appendChild(products);
wrapper.appendChild(dates);
container.appendChild(wrapper);
}
}
bodyContent()
//function that sorts ads by properties
function sortBy(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
//I want to have eventlisteners on each option selected but then not sure how to implement this since I'm using a loop to display all the ads
function myFunction(value) {
ads.sort(sortBy(value));
bodyContent()
}
body {
font-family: Arial, Helvetica, sans-serif;
}
div {
margin: 5%;
}
.wrapper {
border: 2px solid #3abac4;
padding:5%;
}
h4 a {
text-decoration: none;
color: #fff;
background-color: #3abac4;
margin: 10px;
padding: 10px;
}
h4 a:hover {
color: #3abac4;
background-color: #fff;
border: 2px solid #3abac4;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="sortList">
<select id="selectSort" onchange="myFunction(this.value)">
<option value="title">Title</option>
<option value="description">Description</option>
<option value="start_date">Start date</option>
<option value="end_date">End date</option>
<option value="offer">Most products</option>
<option value="num_of_products">Least products</option>
</select>
</div>
<div id="container"></div>
</body>
</html>
I'll only ask to the Question's title (EDIT: you've edited the title). The DOM stuff is easy (and frankly I didn't work with it for last few years).
To sort by property:
ads.sort((a, b) => a[selectedProp] > b[selectedProp] ? 1 : -1)
Then you should somehow update your view (don't know how to do it, I am spoiled with frameworks like angular, react etc.), probably using React or Vue.js. Doing a loop is good. You just loop the same array. The only thing you need is to update the view.
Extreme newbie here but am learning as fast as I can; hands in JavaScript, HTML, CSS. Over my head though with this specialty stuff. (please be kind ... trying to get there)
I've got a JSON file of quotes that are linked to everyday of the year (by month date). I want to use a Month/Day calendar picker (like attached image) for a user to select. End result will be a quote for selected month/day. Nothing random. Specific quotes for specific dates.
Year does not matter, so prefer not to use it.
I'm using jQuery and moment.js on what is to be a cross-platform mobile app (launching w/iOS though). Hoping phonegap will spare me more growing pains.
I've searched forums and looked through StackOverFlow and some of StackExchange to find an answer. I've tried my hand at different suggestions but no success. My code is kind of convoluted but here it is.
(This is my first post and have tried to adhere to 4 space rule. Not sure based on reviewing before post -- but it is 4 spaces in code block.)
$(document).ready(function() {
var calendar = new Date().getDate();;
var dd = new Date().getDate();
var mm = new Date().getMonth() + 1;
var dailyQuote = {
"April 19": {
"quote": "Blessed is the one who considers the poor! . . .",
"refTag": "Psalm 41:1-2"
},
"April 20": {
"quote": "We who are strong have an obligation....",
"refTag": "Romans 15:1"
},
"April 21": {
"quote": "Remember those who are in prison, ....",
"refTag": "Hebrews 13:3"
},
"April 22": {
"quote": "Pride goes before destruction....",
"refTag": "Proverbs 16:18",
"quote2": "Before destruction a manโs heart is haughty, but humility comes before honor.",
"refTag2": "Proverbs 18:12"
},
"April 23": {
"quote": "Let no one deceive himself....",
"refTag": "1 Corinthians 3:18-21"
},
"April 24": {
"quote": "Haughty eyes and a proud heart, the lamp of the wicked, are sin.",
"refTag": "Proverbs 21:4"
},
"December 30": {
"quote": "I have fought the good fight, I have finished the race, ...",
"refTag": "2 Timothy 4:7-8"
},
"December 31": {
"quote": "May the Lord fulfill all your petitions!",
"refTag": "Psalm 20:5"
}
};
console.log(dailyQuote);
var bCode = moment().format("MMMM D");
$("#selectedDate").html(moment().format("MMMM D"));
$("#selectedVerse").html(dailyQuote[bCode].quote);
$("#selectedVerseRefTag").html(dailyQuote[bCode].refTag);
$("#selectedVerse2").html(dailyQuote[bCode].quote2);
$("#SelectedVerseRefTag2").html(dailyQuote[bCode].refTag2);
$("#selectedTime").html(moment().format("MMMM Do YYYY, h:mm:ss a"));
document.getElementById("script").innerHTML = dailyQuote;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<div class="calendarPicker">
<h1>Pick a Date: <input type="date" id="calendar" format="MM D"></h1>
<input type="text" id="quote" value="insert w/Quote>>>">
<textarea id="script" value="Text area"></textarea>
<h2 class="quote"> Selected date area: <span id="selectedDate"></span></h2>
</div>
datepicker calendar scroll image
I think you need something like this~
var dailyQuote = {
"April 19": {
"quote": "Blessed is the one who considers the poor! . . .",
"refTag": "Psalm 41:1-2"
},
"April 20": {
"quote": "We who are strong have an obligation....",
"refTag": "Romans 15:1"
},
"April 21": {
"quote": "Remember those who are in prison, ....",
"refTag": "Hebrews 13:3"
},
"April 22": {
"quote": "Pride goes before destruction....",
"refTag": "Proverbs 16:18",
"quote2": "Before destruction a manโs heart is haughty, but humility comes before honor.",
"refTag2": "Proverbs 18:12"
},
"April 23": {
"quote": "Let no one deceive himself....",
"refTag": "1 Corinthians 3:18-21"
},
"April 24": {
"quote": "Haughty eyes and a proud heart, the lamp of the wicked, are sin.",
"refTag": "Proverbs 21:4"
},
"December 30": {
"quote": "I have fought the good fight, I have finished the race, ...",
"refTag": "2 Timothy 4:7-8"
},
"December 31": {
"quote": "May the Lord fulfill all your petitions!",
"refTag": "Psalm 20:5"
}
};
$(document).ready(function() {
var calendar = moment().format("YYYY-MM-DD");
var dateControl = document.querySelector('input[type="date"]');
dateControl.addEventListener(
'change',
function() {
getQuote(this.value);
},
false
);
dateControl.value = calendar;
setQuote(calendar);
function getQuote(date) {
setQuote(date);
}
function setQuote(date) {
var bCode = moment(date).format('MMMM D');
$("#selectedDate").html(bCode);
if (dailyQuote[bCode]) {
$("#selectedVerse").html(dailyQuote[bCode].quote);
$("#selectedVerseRefTag").val(dailyQuote[bCode].refTag);
} else {
$("#selectedVerse").html('');
$("#selectedVerseRefTag").val('No quote for today.');
}
}
});
.pick-date>h1,
.pick-date>input {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<div class="calendarPicker">
<div class="pick-date">
<h1>Pick a Date: </h1> <input type="date" id="calendar" name="calendar" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
</div>
<input type="text" id="selectedVerseRefTag" value=""><br><br>
<textarea id="selectedVerse" value="Text area"></textarea>
<h2 class="quote"> Selected date area: <span id="selectedDate"></span></h2>
</div>