How would you randomize specific objects in an array without repeating? - javascript

I am trying to create a trivia game where there are four clickable options. I have an array that includes my questions, the correct answer, and 3 other options.
const questions = [
{
prompt: "What is the biggest state in the United States?",
answer: "Alaska",
options: ["California", "Texas", "Montana"],
},
{
prompt: "What is the smallest state in the United States?",
answer: "Rhode Island",
options: ["Delware", "Hawaii", "Connecticut"],
},
{
prompt: "Which state is Mt. Rushmore located in?",
answer: "South Dakota",
options: ["New York", "Montana", "North Dakota"],
},
{
prompt: "How many states share a border with mexico?",
answer: "Four",
options: ["Seven", "One", "2"],
},
{
prompt: "What is the oldest town in Texas?",
answer: "Nacogdoches",
options: ["Austin", "Ysleta", "Goliad"],
},
{
prompt: "Which state is the flattest state in the US?",
answer: "Florida",
options: ["Kansas", "Lousiana", "Colorado"],
},
{
prompt: "How many US states are landlocked?",
answer: "16",
options: ["10", "6", "13"],
},
{
prompt: "What state is called ‘The First State’?",
answer: "Delaware",
options: ["New York", "Pennsylvania", "Rhode Island"],
},
{
prompt: "What is the highest point in the United States?",
answer: "Denali",
options: ["Mt. Olympia", "One World Trade Center", "Mt. Bona"],
},
{
prompt: "Which state is closest to Africa?",
answer: "Maine",
options: ["Florida", "South Carolina", "Hawaii"],
},
{
prompt: "Which state has the most water in terms of area?",
answer: "Alaska",
options: ["Michigan", "Texas", "Florida"],
},
{
prompt: "What is the longest river in the United States?",
answer: "Missouri River",
options: ["Nile River", "Mississippi River", "Colorado River"],
},
{
prompt: "What is the deepest lake in the US?",
answer: "Crater Lake",
options: ["Lake Superior", "Lake Tahoe", "Lake Chelan"],
},
{
prompt: "What is the longest road in the United States?",
answer: "Route 20",
options: ["I10", "Route 50", "I80"],
},
{
prompt: "What is the lowest point in the US?",
answer: "Badwater Basin",
options: ["Yellowstone", "Mojave Desert", "New Orleans"],
},
];
let i = 0;
answer1.addEventListener("click", nextQuestion);
answer2.addEventListener("click", nextQuestion);
answer3.addEventListener("click", nextQuestion);
answer4.addEventListener("click", nextQuestion);
function nextQuestion() {
if (i === 14) {
console.log("done");
} else {
i++;
}
topBar.innerHTML = `${i + 1} of 15`;
midBar.innerHTML = questions[i].prompt;
answer1.innerHTML = questions[i].answer;
answer2.innerHTML = questions[i].options[2];
answer3.innerHTML = questions[i].options[0];
answer4.innerHTML = questions[i].options[1];
}
So I have this so far. This issue is is that the correct answer will always be in the place of answer1. How could I randomize the placement of the options and answers without repeating it? Thank you

Related

How to get the address of a location from a google maps URL?

Given a URL of a google maps location, I want to be able to get the address of the location.
For example given this URL:
https://www.google.com/maps/place/Eiffel+Tower/#48.8583701,2.2922926,17z/data=!3m1!4b1!4m5!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d48.8583701!4d2.2944813
I want to get its address:
Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France
Any ideas of how I can do this? I have looked into the google maps API but have not found a way of achieving this.
If you look at the sample URL
https://www.google.com/maps/place/Torre+Eiffel/#48.8583701,2.2922926,17z/data=!3m1!4b1!4m5!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d48.8583701!4d2.2944813
carefully, you will note the following code after '!1s' and before '!8m2':
0x47e66e2964e34e2d:0x8ddca9ee380ef7e0.
This code is the feature id of the place. You can extract this code from the URL using regexp for example. After that you can split the code by ':' and use the second part (0x8ddca9ee380ef7e0) in place details request with parameter cid. Note that this parameter is not publicly documented, but at the moment of writing this undocumented parameter works as expected.
Execute the following request
https://maps.googleapis.com/maps/api/place/details/json?cid=0x8ddca9ee380ef7e0&key=YOUR_API_KEY
You will get the following response
{
html_attributions: [ ],
result: {
address_components: [
{
long_name: "Champ de Mars",
short_name: "Champ de Mars",
types: [
"point_of_interest",
"establishment"
]
},
{
long_name: "5",
short_name: "5",
types: [
"street_number"
]
},
{
long_name: "Avenue Anatole France",
short_name: "Avenue Anatole France",
types: [
"route"
]
},
{
long_name: "Paris",
short_name: "Paris",
types: [
"locality",
"political"
]
},
{
long_name: "Arrondissement de Paris",
short_name: "Arrondissement de Paris",
types: [
"administrative_area_level_2",
"political"
]
},
{
long_name: "Île-de-France",
short_name: "Île-de-France",
types: [
"administrative_area_level_1",
"political"
]
},
{
long_name: "France",
short_name: "FR",
types: [
"country",
"political"
]
},
{
long_name: "75007",
short_name: "75007",
types: [
"postal_code"
]
}
],
adr_address: "Champ de Mars, <span class="street-address">5 Avenue Anatole France</span>, <span class="postal-code">75007</span> <span class="locality">Paris</span>, <span class="country-name">France</span>",
formatted_address: "Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France",
formatted_phone_number: "0 892 70 12 39",
geometry: {
location: {
lat: 48.85837009999999,
lng: 2.2944813
},
viewport: {
northeast: {
lat: 48.8597461302915,
lng: 2.29610765
},
southwest: {
lat: 48.85704816970851,
lng: 2.29251745
}
}
},
icon: "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
id: "fd0cfb424bbd79bf28a832e1764f1c2aa5927714",
international_phone_number: "+33 892 70 12 39",
name: "Eiffel Tower",
opening_hours: {
open_now: true,
periods: [
{
close: {
day: 1,
time: "0045"
},
open: {
day: 0,
time: "0900"
}
},
{
close: {
day: 2,
time: "0045"
},
open: {
day: 1,
time: "0900"
}
},
{
close: {
day: 3,
time: "0045"
},
open: {
day: 2,
time: "0900"
}
},
{
close: {
day: 4,
time: "0045"
},
open: {
day: 3,
time: "0900"
}
},
{
close: {
day: 5,
time: "0045"
},
open: {
day: 4,
time: "0900"
}
},
{
close: {
day: 6,
time: "0045"
},
open: {
day: 5,
time: "0900"
}
},
{
close: {
day: 0,
time: "0045"
},
open: {
day: 6,
time: "0900"
}
}
],
weekday_text: [
"Monday: 9:00 AM – 12:45 AM",
"Tuesday: 9:00 AM – 12:45 AM",
"Wednesday: 9:00 AM – 12:45 AM",
"Thursday: 9:00 AM – 12:45 AM",
"Friday: 9:00 AM – 12:45 AM",
"Saturday: 9:00 AM – 12:45 AM",
"Sunday: 9:00 AM – 12:45 AM"
]
},
photos: [
{
height: 408,
html_attributions: [
"Hauser Quaid Zzyzx"
],
photo_reference: "CmRaAAAAFOGpKiedFvYYu7R7qLkxqdY2GqcGqmHNPvny_a2dYV81XTFC2RL0ybS-NZg_oQUa0Fa-U178CBPLmCx8Xz_PTt16jW87WUm9rdYHoVklaAeH52pVuCwW1014vu-5EboPEhDHt-Gt9o_2tEKXWt6FQVXwGhSnNEX49VjoMdiPlXPaZ3z18yN-_A",
width: 612
},
{
height: 3888,
html_attributions: [
"Gonçalo Borralho"
],
photo_reference: "CmRaAAAAJLOe9SSk1G-d8KTm5dFPw-CAvXd7SK5eg0AS2_zF7eTsNGDJZptupKLRodFE9GfdpRcxYhTzIWkoBx2EIEPamq_A5G8A7Q905KlIkDln6Kz83xIDDjY5D4FBHCQnySriEhBRME9npMoGWKdfz2HDJnV3GhRQT2YZDE2axrCDGbWguRiYaDP4jw",
width: 2592
},
{
height: 600,
html_attributions: [
"Maria Goryunova"
],
photo_reference: "CmRaAAAAbZO6_2CHj1TxxpNu9-un01rYHMy7v7MhiWB4auCwwqp8a2xkSlWiheQZQBG6kGHp0qPkn6NNwhup9teVKZUjmPTqvMFhI5ER0WyX-RrhHFStBMa5it6qT6V7H4VI297KEhCr-hcQDRTtE0q3fEqWKlnXGhRme7pNMXQRYxuXIpJAkWtEVxQ_Mw",
width: 600
},
{
height: 4160,
html_attributions: [
"praveen dhingra"
],
photo_reference: "CmRaAAAA_WjfpbIVJ5zVIy1j-0Q2VKwxGjbGQNzcD9F6rIFEAVqQEvrv_OSrfTX3Mac8NwDopr1rl63jZGUbExJkQDckM-DGr9TQqfT7FTLbSxtOra6NTIa5jijTkTh-Ivw_uB1dEhCeiq5yjZZjBfRnmc2SLUxYGhQ4XOKL7PlMZpgZ_Be_b3oK8hHwIw",
width: 2080
},
{
height: 4000,
html_attributions: [
"H.İbrahim Üzmezoğlu"
],
photo_reference: "CmRaAAAAmLIY1pgIGZL720khB_lfo956P3UX_rnBZG0KxTImqJCR8sZGHXGv7IdcIM_c5kaIYLkeG-WwXehU367cLhN8ordS0lqCITaiXL2w2HdL0mABPcr3JYw4fGBsv_I4ScK-EhCJDIwwlPEel5mXVt0Ype10GhTbA4MsOMt9mVegngR7AOIjqYiX3w",
width: 3000
},
{
height: 3648,
html_attributions: [
"Kerem Enginar"
],
photo_reference: "CmRaAAAACLc5gwLJxZRPVQI-5X_iI1TyaFwc6HA1aFYeSzDAU7514FU_iEYWxVEEgpavyXmC4PU1x-NVvCSOyxBVEbcX2wgYp6dMsIgg2wK11HvlZW2OxHAVsiDv2m3Qk7hXyhApEhCiR3DSFJ8dwHtsH4OMKCuqGhRcFAIpkIp0XvhAXpHmkFRnfVcGCQ",
width: 1744
},
{
height: 3968,
html_attributions: [
"LUIS ROLDAN"
],
photo_reference: "CmRaAAAAwyx_YEdelPVTlgqw9KWqXuXKuzDRS9m6gyemO9HIIJGNSVfW-kYClF8TeKqxZt9YvSe9SnhmCMzFGr5fKeKUbiTIz0wAFNvZysdqT9TV8nJ009m-FTtB0Rx8RC0h70e5EhCIUcnE8JgPBue7IUmwOA0fGhRzbGCB5-35S34i7AIaJXu9CEE2jg",
width: 2976
},
{
height: 4032,
html_attributions: [
"Frank Rafaelsen Lian"
],
photo_reference: "CmRaAAAAFTSEd1eR_zkspc7ksK3S22nq69UXYtW8DGR7B7yfCiL2Q_IJl29yofflEj5HQ8ANuLyQR-NlSYGN3FhnC5jj-zGqUR4wTv-_B-imPEnCvq2mHDz_gO43bbc2xQmcGsecEhCR7Uryl1QTECndlU0f94uuGhT4CYw5JLAO-27Gi_cIdK9Ic1YFxA",
width: 3024
},
{
height: 3024,
html_attributions: [
"Wadih Antoun"
],
photo_reference: "CmRaAAAA6A_JRLItYa05p9NcXapox8ROY_h2id9AVewX1wChZPP8iBZvA1JHQo9qEFGwyTUuXQ9Pu7-xXgKJkgCepp2SkSdprRjBfvcmt-ZQUH4LjigupU1AAqzMZRVXKbZ2WjHgEhBAIQ2EgygtvhtZSy6Y7QJbGhTLTj0jgWPIJVTxHgUFzqWbnnnymw",
width: 4032
},
{
height: 4224,
html_attributions: [
"Steve Bird"
],
photo_reference: "CmRaAAAAGbShlT71nLeJHL5sagdgtjssvWCBhDsqPsZ9xeNXu48iFlBsRoRarZZTMUJSK0p2H91Rg27XE8HFCRvvgxLTctA9eJhCktsDoOjP33zw04sX19jrrMhGpS0kOemTV-daEhAz41RPzVtazLhOYKdmkSHqGhRPd9g9S94_N0HrxV9oRcPCHfd2ZQ",
width: 2368
}
],
place_id: "ChIJLU7jZClu5kcR4PcOOO6p3I0",
plus_code: {
compound_code: "V75V+8Q Paris, France",
global_code: "8FW4V75V+8Q"
},
rating: 4.6,
reference: "ChIJLU7jZClu5kcR4PcOOO6p3I0",
reviews: [
{
author_name: "Margaret Bagdon",
author_url: "https://www.google.com/maps/contrib/115820855361415255644/reviews",
language: "en",
profile_photo_url: "https://lh5.googleusercontent.com/-L8M8JctpleE/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3reM2h_11AXwURDawihkuOG34a9MQg/s128-c0x00000000-cc-rp-mo-ba4/photo.jpg",
rating: 4,
relative_time_description: "in the last week",
text: "I purchased tickets on line for 9:00 on a Tues in June. Couldn't print my tickets because of a problem with the account so we showed up early to have them printed. We we're lucky no one was in line at the info booth. We waited in the line (30 minutes) for the time slot we booked. The line to purchase tickets was much longer so I recommend you buy in advance. We rode the glass side lift to the first observation deck and immediately got in line to go to the summit. Waited about 15 minutes. The top was crowded and we watched the sunset from the top. The views are nice so I think it was worth it. You can purchase a small glass of champagne if you want a toast at the top. We took the lift down and stopped for a drink and a rest. We walked the remainder of the way and got down in time to see the brief light show. Good view on the lawn. I would recommend stopping here if it is your first time in Paris and you don't mind heights.....be prepared to wait....and it will be crowded.....and expensive...",
time: 1563234656
},
{
author_name: "Shahrukh Naeem",
author_url: "https://www.google.com/maps/contrib/102499154519714023927/reviews",
language: "en",
profile_photo_url: "https://lh4.googleusercontent.com/-qQBtFB0REZI/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rd9bYBR5bZcH6BMYaRd5yv2Gw79WQ/s128-c0x00000000-cc-rp-mo-ba5/photo.jpg",
rating: 5,
relative_time_description: "2 weeks ago",
text: "Wonderful romantic place. Must visit with loved ones. Breathtaking view from up the level 2. People can also buy an additional Ticket and go up to the next level to even have a wonderful view or dine with love. Sure a wonder to visit and of course go on top of it. So many romantic couples were taking romantic photos in this structure. In the night there was a five minute light show which has to be viewed from a distance to enjoy how magnificently people made this city a tourist attraction because of this structure",
time: 1562399468
},
{
author_name: "Anca Chelaru",
author_url: "https://www.google.com/maps/contrib/113471456079540231282/reviews",
language: "en",
profile_photo_url: "https://lh4.googleusercontent.com/-UnNJLd9XjiM/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rcGIic0U1eWvnrKz-xfp2s6mqI2vg/s128-c0x00000000-cc-rp-mo-ba3/photo.jpg",
rating: 5,
relative_time_description: "a week ago",
text: "I loved it! It is better than Empire State Building because you see the empty space going up/down and it gives you an adrenaline rush, that you don't feel in a building. You can take the stairs on the way down, better than the elevator. At the restaurant level, there is glass floor, so you can see all the way down. The gift store at the restaurant level is better than the on on top, it has more staff. Buy the tickets online, saves time. You can easily spend here 1/2 a day.",
time: 1562661564
},
{
author_name: "Jeroen van der Linde",
author_url: "https://www.google.com/maps/contrib/109990025751819839602/reviews",
language: "en",
profile_photo_url: "https://lh5.googleusercontent.com/-g03RbnKDnJ8/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3ren8G7DFs0oZV0hkiYaBdYRydQleQ/s128-c0x00000000-cc-rp-mo-ba6/photo.jpg",
rating: 5,
relative_time_description: "a week ago",
text: "Of course one of the main tourist attractions in Paris, France and even the world. Elevators work now but you can still take the stairs if you want to have a cheaper option to go up. T The direct area is fenced off with high bullet proof glass walls and protected entrances at the sides. Visitors are subject to some screening. If you are looking for pictures of the Eiffel Tower you can also visit the lawn or pond at the sides for better views.",
time: 1562921719
},
{
author_name: "Pratap Ramamoorthy",
author_url: "https://www.google.com/maps/contrib/117384906578505429183/reviews",
language: "en",
profile_photo_url: "https://lh3.googleusercontent.com/-Oo8pn66vGDM/AAAAAAAAAAI/AAAAAAAAA7g/rXZn8xS2bPg/s128-c0x00000000-cc-rp-mo-ba6/photo.jpg",
rating: 5,
relative_time_description: "a month ago",
text: "Wonderful romantic place. Must visit with loved ones. Breathtaking view from up the level 2. People can also buy an additional Ticket and go up to the next level to even have a wonderful view or dine with love. Sure a wonder to visit and of course go on top of it. So many romantic couples were taking romantic photos in this structure. In the night there was a five minute light show which has to be viewed from a distance to enjoy how magnificently people made this city a tourist attraction because of this structure.",
time: 1559894189
}
],
scope: "GOOGLE",
types: [
"premise",
"point_of_interest",
"establishment"
],
url: "https://maps.google.com/?cid=10222232094831998944",
user_ratings_total: 166537,
utc_offset: 120,
vicinity: "Champ de Mars, 5 Avenue Anatole France, Paris",
website: "http://www.toureiffel.paris/"
},
status: "OK"
}
The formatted_address field contains address you are looking for "Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France".
I hope this helps!

'addEventListener' of undefined

I am trying to make it so that when the user clicks one of the 30 teams, the team that is clicked is queried with the Giphy API.
The giphy API key used is the public API key.
// all 30 NBA Teams //
var predefinedButtons = [
"Atlanta Hawks",
"Boston Celtics",
"Brooklyn Nets",
"Charlotte Hornets",
"Chicago Bulls",
"Cleveland Cavaliers",
"Dallas Mavericks",
"Denver Nuggets",
"Detroit Pistons",
"Golden State Warriors",
"Houston Rockets",
"Indiana Pacers",
"LA Clippers",
"LA Lakers ",
"Memphis Grizzlies",
"Miami Heat",
"Milwaukee Bucks",
"Minnesota Timberwolves",
"New Orleans Hornets",
"New York Knicks",
"Oklahoma City Thunder",
"Orlando Magic",
"Philadelphia Sixers",
"Phoenix Suns",
"Portland Trail Blazers",
"Sacramento Kings",
"San Antonio Spurs",
"Toronto Raptors",
"Utah Jazz",
"Washington Wizards"
];
console.log(predefinedButtons);
// The Buttons added dynamically //
var $nbaTeams;
var nbaButtons = function nbaGiphy() {
for ( i in predefinedButtons ) {
$nbaTeams = $("<button class='.btn btn-secondary' 'onclick='getNBAGiphy()''>").text(predefinedButtons[i]);
$("#nbaTags").append($nbaTeams);
}
}
nbaButtons();
// The code below is where the event listener is 'undefined' //
function getNBAGiphy() {
var nbaSearchGifs;
nbaSearchGifs.addEventListener('click', function() {
nbaSearchGifs = $(".btn btn-secondary").val();
xhr = $.get("http://api.giphy.com/v1/gifs/search?q="+nbaSearchGifs+"&api_key=dc6zaTOxFJmzC&limit=15");
xhr.done(function (response) {
console.log("success got data", response);
nbaTeamData = response.data
$("#giphyContent").html("");
console.log(nbaSearchGifs);
})
});
}
getNBAGiphy();
You are declaring variable and you have not assigned any value to it. So by default it is undefined. Code i am referring to is:
function getNBAGiphy() {
var nbaSearchGifs;
nbaSearchGifs.addeventListner

Selection .val has strange, in-understandable value (Chosen plugin)

In Ruby-on-Rails, I am using the Chosen plugin on a multiselector for a list of provinces as below:
<%= select_tag :provinces,
options_for_select(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{:multiple => true, class: 'chosen-select chzn-select',
:data => {:placeholder => 'Filter Provinces/States'}}%>
I also have a selector in a form field on the same page like so:
<%= f.select :province_ids,
(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{ include_blank: true }, {
multiple: true, data: {placeholder: 'Filter Provinces/States'} }
%>
Finally, I have a Javascript function that synchronizes the two when #provinces, with class .chzn-select changes:
var selectedVals = [];
$(".chzn-select").chosen().change(function() {
$("#provinces option:selected").each(function () {
console.log ("this value is " + ($(this).val));
selectedVals.push($(this).val);
});
$("#education_plan_province_ids").empty();
for (var i = 0; i < selectedVals.length; i++) {
console.log (selectedVals[i] + " selected");
$("#education_plan_province_ids").append($("<option>" + selectedVals[i] + "</option>")).prop("selected", true);
}
});
However, in my console, instead of getting an output, "this value is alabama" for example, I get the following:
this value is function (a){var b,c,d,e=this[0];{if(arguments.length)return
d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d
a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e
e+="":n.isArray(e)&&(e=n.map(e,function(a){return
null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase(
],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return
b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!=
(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c
c.replace(bc,""):null==c?"":c)}}
So not surprisingly, I am very confused as to why this is happening!
For a final piece of info, here is all_provinces_captions, all_provinces_ids, canada_provinces_with_caption, and usa_provinces_with_caption in the DataHelper, all arrays:
def self.usa_provinces_with_caption
[["Alabama", "alabama"], ["Alaska", "alaska"], ["Arizona", "arizona"], ["Arkansas", "arkansas"], ["California", "california"], ["Colorado", "colorado"], ["Connecticut", "connecticut"], ["Delaware", "delaware"], ["District Of Columbia", "district of columbia"], ["Florida", "florida"], ["Georgia", "georgia"], ["Hawaii", "hawaii"], ["Idaho", "idaho"], ["Illinois", "illinois"], ["Indiana", "indiana"], ["Iowa", "iowa"], ["Kansas", "kansas"], ["Kentucky", "kentucky"], ["Louisiana", "louisiana"], ["Maine", "maine"], ["Maryland", "maryland"], ["Massachusetts", "massachusetts"], ["Michigan", "michigan"], ["Minnesota", "minnesota"], ["Mississippi", "mississippi"], ["Missouri", "missouri"], ["Montana", "montana"], ["Nebraska", "nebraska"], ["Nevada", "nevada"], ["New Hampshire", "new hampshire"], ["New Jersey", "new jersey"], ["New Mexico", "new mexico"], ["New York", "new york"], ["North Carolina", "north carolina"], ["North Dakota", "north dakota"], ["Ohio", "ohio"], ["Oklahoma", "oklahoma"], ["Oregon", "oregon"], ["Pennsylvania", "pennsylvania"], ["Rhode Island", "rhode island"], ["South Carolina", "south carolina"], ["South Dakota", "south dakota"], ["Tennessee", "tennessee"], ["Texas", "texas"], ["Utah", "utah"], ["Vermont", "vermont"], ["Virginia", "virginia"], ["Washington", "washington"], ["West Virginia", "west virginia"], ["Wisconsin", "wisconsin"], ["Wyoming", "wyoming"]]
end
def self.canada_provinces_with_caption
[["Alberta", "alberta"], ["British Columbia", "british columbia"], ["Manitoba", "manitoba"], ["New Brunswick", "new brunswick"], ["Newfoundland", "newfoundland"], ["Northwest Territories", "northwest territories"], ["Nova Scotia", "nova scotia"], ["Nunavut", "nunavut"], ["Ontario", "ontario"], ["Prince Edward Island", "prince edward island"], ["Quebec", "quebec"], ["Saskatchewan", "saskatchewan"], ["Yukon", "yukon"]]
end
def self.all_provinces_captions
usa_provinces_with_caption.map { |x| x.first } + canada_provinces_with_caption.map { |x| x.first }
end
def self.all_provinces_ids
usa_provinces_with_caption.map { |x| (Province.find_by name: x.first).id} + canada_provinces_with_caption.map { |x| (Province.find_by name: x.first).id }
end
It looks like your missing the parenthesis for the .val method. Try the following:
$(this).val()
Try, on your rendered page, inspect the chosen element and check the element (it usually is hidden) and pick the id there to replace
$(".chzn-select").chosen().change(function() {
}
for
$("#your-id").change(function() {
// do some stuff
$("#your-id").trigger("liszt:updated"); //This is necessary when you change your chosen select options, so it refresh the component
}
Hope it helps!

Load JSON file into JavaScript variable

So, I need to put the following code into a JSON file and load it into a separate JavaScript file:
var allQuestions = [{
question: "What is Elvis Presley's middle name?",
choices: ["David", "Aaron", "Eric", "Jack"],
correctAnswer: 1
}, {
question: "Who is the singer of the Counting Crows?",
choices: ["Adam Duritz", "John Adams", "Eric Johnson", "Jack Black"],
correctAnswer: 0
}, {
question: "Who is the Queen of Soul?",
choices: ["Mariah Carey", "Whitney Houston", "Aretha Franklin", "Beyonce"],
correctAnswer: 2
}, {
question: "Which famous group was once known as The Quarrymen?",
choices: ["The Beatles", "The Birds", "The Who", "Led Zeppelin"],
correctAnswer: 0
}];
In other words, the contents of allQuestions need to go in a JSON file and then loaded into the allQuestions variable in a separate JavaScript file. What would the JSON file look like and how would I load it into the allQuestions variable?
Try using JSON.stringify() , $.getJSON()
What would the JSON file look like
"[
{
"question": "What is Elvis Presley's middle name?",
"choices": [
"David",
"Aaron",
"Eric",
"Jack"
],
"correctAnswer": 1
},
{
"question": "Who is the singer of the Counting Crows?",
"choices": [
"Adam Duritz",
"John Adams",
"Eric Johnson",
"Jack Black"
],
"correctAnswer": 0
},
{
"question": "Who is the Queen of Soul?",
"choices": [
"Mariah Carey",
"Whitney Houston",
"Aretha Franklin",
"Beyonce"
],
"correctAnswer": 2
},
{
"question": "Which famous group was once known as The Quarrymen?",
"choices": [
"The Beatles",
"The Birds",
"The Who",
"Led Zeppelin"
],
"correctAnswer": 0
}
]"
how would I load it into the allQuestions variable?
$.getJSON("/path/to/json", function(data) {
var allQuestions = data;
})
jsfiddle https://jsfiddle.net/dydhgh65/1
You can use the ES6 fetch API, like so:
// return JSON data from any file path (asynchronous)
function getJSON(path) {
return fetch(path).then(response => response.json());
}
// load JSON data; then proceed
getJSON('/path/to/json').then(data => {
// assign allQuestions with data
allQuestions = data;
}
Here is how to do it using async and await.
async function getJSON(path, callback) {
return callback(await fetch(path).then(r => r.json()));
}
getJSON('/path/to/json', data => allQuestions = data);
Try this:
var myList;
$.getJSON('JsonData.json')
.done(function (data) {
myList = data;
});

How do I shuffle an array within an array?

SETUP Description:
I am building a trivia game that has a spinner. This spinner is split up into 6 categories (the 6th category being ALL previous 5 categories combined). The first 5 categories will have it's own set of questions. Once the spinner stops on a category a form appears that will ask a series of questions in order according to it's category. Each question has 3 choices, 1 of them being the correct choice.
Below is a short question bank array to illustrate what I am thinking:
```
var questionBankArray =
[{
category: "Category1",
question: "What does the following expression return? <br> 3 / 'bob';",
choices: ["undefined", "ReferenceError", "NaN"],
correctAnswer: "NaN"
},{
category: "Category1"
question: "What is a method?",
choices: ["Used to describe an object.", "A function assigned to an object.", "Performs a function on one or more operands or variables."],
correctAnswer: "A function assigned to an object."
},{
category: "Category2"
question: "Which company first implemented the JavaScript language?",
choices: ["Netscape Communications Corp.", "Microsoft Corp.", " Sun Microsystems Corp."],
correctAnswer: "Netscape Communications Corp."
},{
category: "Category2"
question: "When was the first release of a browser supporting JavaScript?",
choices: ["1996", "1995", " 1994"],
correctAnswer: "1995"
},
];
```
I would like to go through the questionBanArray of objects, and by category, shuffle within that category. I also want to be able to shuffle the choices within each question of that category. How would I go about this? Would it be harder easier to rewrite it to look like this:
questionBankArray =
[{
CategoryBank1:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}],
CategoryBank2:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
I think the ideal structure would be something like this:
questionBankArray =
[{
category:"first category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
},
{
category: "second category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
Create a shuffle function:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
Start looping over your outer array and go deeper and deeper, applying the shuffle function from the most inner level to the outer array
for (var category in questionBankArray) {
for (var question in category.questions) {
shuffle(question.choices);
}
shuffle(category);
}
shuffle(questionBankArray);

Categories

Resources