Change image and quote on a click? - javascript

I'm creating a quick little page. I'm just learning JavaScript and it's taking some getting used to. I was able to create a page that changes quotes when the image is clicked. Now, I want the image to change with the quotes. So it will be: click on image 1, and image 2 will appear with quote 2. Click on image 2, and image 3 will appear with quote 3.
This is a pretty simple task but I have not been able to find an easy solution. I've spent a couple hours on this, which is sort of depressing.
Here's the page: https://aprilehrlich.github.io/dataint/
Following is what I've got in HTML:
<!DOCTYPE html>
<html>
<head>
<title>Ida B. Wells</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img id="MainProductImage"" src="https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg" width="500px"" id="myImg">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
</body>
</html>
JavaScript:
$(document).ready(function() {
var quote1 = "“Quote 1.”";
var quote2 = "“Quote 2”";
var quote3 = "“Quote 3”";
var quote4 = "“Quote 4”";
var quote5 = "“Quote 5”";
var quote6 = "“Quote 6”";
var quote7 = "“Quote 7”";
var quote8 = "“Quote 8”";
var quote9 = "“Quote 9”";
var quote10 = "“Quote 10”";
$("img").click(function() {
var currentQuote = $("h1").text();
$("h1").fadeOut(0);
if (currentQuote == quote1) {
$("h1").text(quote2);
}
if (currentQuote == quote2) {
$("h1").text(quote3);
}
if (currentQuote == quote3) {
$("h1").text(quote4);
}
if (currentQuote == quote4) {
$("h1").text(quote5);
}
if (currentQuote == quote5) {
$("h1").text(quote6);
}
if (currentQuote == quote6) {
$("h1").text(quote7);
}
if (currentQuote == quote7) {
$("h1").text(quote8);
}
if (currentQuote == quote8) {
$("h1").text(quote9);
}
if (currentQuote == quote9) {
$("h1").text(quote10);
}
$("h1").fadeIn(1000);
});
})

You have to use the attr (attribute) function to change the src element. Here's an example. I made your code a little bit more dynamic so you can set as many quotes as you wish without changing your code:
HTML:
<img id="MainProductImage" src="https://s-media-cache-ak0.pinimg.com/564x/2a/b4/e7/2ab4e74ad637f9c8ecb792b8b7d605a6.jpg" id="myImg" data-current-quote="0">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
Javascript:
$(document).ready(function(){
//Quotes/Image Array
var quotes = [
{ quote: "Quote1", img: "https://s-media-cache-ak0.pinimg.com/564x/2a/b4/e7/2ab4e74ad637f9c8ecb792b8b7d605a6.jpg"},
{ quote: "Quote2", img: "https://s-media-cache-ak0.pinimg.com/564x/af/52/03/af5203d09a0be9c9e655786c88c1d8b7.jpg"},
{ quote: "Quote3", img: "https://s-media-cache-ak0.pinimg.com/564x/04/37/3c/04373c4f98797b202d13b9882e137690.jpg"}
];
$("img").click(function(){
var img = $("#MainProductImage"),
//We look for the next quote, if it's the last we go to the beginning
currentQuote = img.data("current-quote") === quotes.length -1 ? 0 : img.data("current-quote") + 1,
nextQuote = quotes[currentQuote];
//Set the current quote index in a data attribute
img.data("current-quote", currentQuote);
$("h1").fadeOut(0);
//Change the text
$("h1").text(nextQuote.quote);
//Change the image
img.attr("src", nextQuote.img);
});
});
Fiddle: https://jsfiddle.net/p2bus29y/2/

var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
},
{
"ID": 2,
"Name": 'Industrial Solar Power Plants',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'So as to become a preferential business name, we are thoroughly engrossed in shipping an inclusive collection of Industrial Solar Power Plants.',
"ImageUrl": 'assets/images/Products/Industrial_Solar_Power_Plants.jpg',
},
{
"ID": 3,
"Name": 'On Grid Solar Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 1.1 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Plant.jpg',
},
{
"ID": 4,
"Name": 'On Grid Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Power Plant. To sustain the quality, our products are made under the guidance of industry top professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Power_Plant.jpg',
},
{
"ID": 5,
"Name": 'Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of Solar Power Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/Solar_Power_Plant.jpg',
},
]
}
]
function GetProducts() {
var products = data;
$.each(products, function () {
//var product = products.filter(filterByID)
var product = this;
$('#ProductDetails').append('<h2 class="text-center">' + this.CategoryName + '</h2>');
var details = product;
$.each(details.CategoryProducts, function () {
tempData = tempData + '<div class="col-md-4 col-sm-6">' +
'<div class="project-box">' +
'<div class="frame-outer">' +
'<div class="frame">' +
'<img style="width:350px;" src="' + this.ImageUrl + '" class="attachment-340x220 size-340x220 wp-post-image" alt="">' +
'</div>' +
'</div>' +
'<div class="text-box">' +
'<h3><a>' + this.Name + '</a></h3>' +
'<div class="tags-row">' +
'<a class="link">' + this.SubTitle + '</a>' +
'</div>' +
'<p>' + this.Description + '</p>' +
//'More Details' +
'</div>' +
'</div>' +
'</div>';
});
$('#ProductDetails').append('<div class="row">' + tempData + '</div>');
tempData = '';
});
}
Here, it's my own code may be it helps you. It does not belong to your code but you can understand and maybe you need to do like this

I have created an array with the quote and image sources. I have incremented a counter to define the index of the array. I have also made it so the quote fades back in once everything is done, so the text doesn't change until it has faded out.
$(document).ready(function(){
// set array of quotes and images
var content = [
["“Quote 1.”", "https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg"],
["“Quote 2.”", "http://www.stevensegallery.com/460/300"],
["“Quote 3.”", "http://www.stevensegallery.com/300/200"],
["“Quote 4.”", "http://www.stevensegallery.com/460/300"],
["“Quote 5.”", "http://www.stevensegallery.com/300/200"],
["“Quote 6.”", "http://www.stevensegallery.com/284/196"],
["“Quote 7.”", "http://www.stevensegallery.com/300/200"],
["“Quote 8.”", "http://www.stevensegallery.com/460/300"],
["“Quote 9.”", "http://www.stevensegallery.com/300/200"],
["“Quote 10.”", "http://www.stevensegallery.com/284/196"],
];
// set counter to 1
var count = 1;
$("img").click(function(){
// check is end of array reached and start from beginning
count == content.length ? count = 0 : "";
// fade h1 out
$("h1").fadeOut(500, function() {
// use counter to get the correct index of array to change the h1 to the relevent quote
$("h1").text(content[count][0]);
// use counter to get the correct index of array to change the h1 to the relevent image source
$("img").attr("src", content[count][1]);
// fade h1 back in after everything else is done
$("h1").fadeIn(500);
// increment count by 1
count++;
});
});
});
<img id="MainProductImage"" src="https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg" width="500px"" id="myImg">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

have populated radio buttons, want to use submit button to print the value out

Is there a way to grab the values from the radio buttons? say it gets populated in the radio button and the options are Abuelos, Boogie Burger, Pad Thai, Coalition Pizza, Wild Eggs. Is there a way I can pull those values out and have it print out after hitting a submit button?
I also don't want the value to be redirected to another page. I just want it to print out below the submit button. I also don't want the user to be able to select a value after they hit the submit button
I am trying to make a voting poll where options are taken from multiple arrays and then someone can pick a value from the radio button and hit a submit button with their option printed out. That way the user can tell what they voted for.
part of the HTML code:
<form action="" id="food-form"></form>
Javascript code:
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
You can use document.querySelector('input[name=food]:checked').value to get the selected value.
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
function print() {
var t = document.querySelector('input[name=food]:checked');
if (t == null)
console.log('No value selected');
else
console.log(t.value);
}
<form action="" id="food-form">
</form>
<input type="submit" id="btn" value="Submit" onClick="print()">

Send a random number from one function to be used by another.

I am working on a word game with javascript.
I need to pass a random number created by an onclick event in one function to another. The other function fires with a onclick event.
(I allready tried to send the random number as a parameter to the new
funcion and it worked, but not with the clickevent)
The first method, spelet.word, picks a random eng word fron an array of 10 words.
The second method, spelet.answer, checks if it is correctly spelled. It does so by taking the same randomly generated number from first method to pick the right word for the array of words.
Problem is I cant acess the randomly created number from the first method with onclick.
The relevant HTML
<form>
<input type="text" value="eng" id="eng" />
<!-- the english word-->
<input type="text" value="sve" id="sve" />
<!-- the swedish word-->
<input type="button" value="Nytt Ord" onclick='spelet.word();' />
<br />
<!-- Generates a random english word from an array of 10 words-->
<input type="button" value="Svara" onclick='spelet.answer();' />
<br />
<!-- The user use this button to submit the swedish word-->
</form>
var $Lars = {};
var objwords = //Måste ha som global för att alla metoder ska nå den.
{
ord: [{
eng: "bird",
sve: "fågel"
}, {
eng: "car",
sve: "bil"
}, {
eng: "food",
sve: "mat"
}, {
eng: "coffee",
sve: "kaffe"
}, {
eng: "water",
sve: "vatten"
}, {
eng: "woman",
sve: "kvinna"
}, {
eng: "cup",
sve: "kopp"
}, {
eng: "pen",
sve: "penna"
}, {
eng: "beer",
sve: "öl"
}, {
eng: "desert",
sve: "öken"
}, {
eng: "stone",
sve: "sten"
}]
}
$Lars.Play = function()
{
var c;
this.word = function() {
//---------- doing a random number-----------------//
var c = Math.floor(Math.random() * 10) + 1;
//spelet.answer(c); DID NOT WORK
document.getElementById('eng').value = objwords.ord[c].eng;
var i = 0; //using the random number to pick up en english word
for (i = 0; i < objwords.ord.length; i++) {
document.getElementById('eng').value = objwords.ord[c].eng;
}
document.getElementById('nr').value = c;
//return c; DID NOT WORK
}
this.answer = function() //the same random number picks up the swedish word and
//check if it is correct spelled
{
var svaret = document.getElementById('sve').value;
var q = 0;
for (q = 0; q < objwords.ord.length; q++) {
if (objwords.ord[c].sve == svaret) {} //something happens when correct answer;}
else {} //something happens when incorrect answer;}
}
}
}
var spelet = new $Lars.Play();
You need a more globaly scoped variable for that. A minimal example:
function Play (){
this.c = -1;
}
Play.prototype.word = function(){
this.c = Math.floor(Math.random() * 10) + 1;
console.log("Produced: " + this.c);
}
Play.prototype.answer = function(){
console.log("Got " + this.c);
}
var playit = new Play();
playit.word();
playit.answer();
playit.word();
playit.answer();
You don't need to spell the protoypes out, I just thought it would make it more obvious.

Not getting proper output when shifting values in array position

I am having 1 Array in which my Source and Destination are like this:
markers.push({
"Location": "Chicago",
"IsLocation": "Yes"
});
markers.push({
"Location": "Los Angeles",
"IsLocation": "Yes"
});
Now when i will create points with my dynamic textbox then i would
like to add those all points in between source and destination.
Scenario 1:1st dynamic textbox with input say for Eg:abc
markers[0]:Chicago
markers[1]:abc
marker[2]:Los Angeles.
Scenario 2:2nd dynamic textbox with input say for Eg:pqr
markers[0]:Chicago
markers[1]:abc
markers[2]:pqr
marker[3]:Los Angeles.
Scenario 3:3rd dynamic textbox with input say for Eg:lmn
markers[0]:Chicago
markers[1]:abc
markers[2]:pqr
markers[3]:lmn
marker[4]:Los Angeles.
My first position will be fixed.
Code:
// Code goes here
var cnt = 1;
var maxNumberOfTextboxAllowed = 5;
var autocomplete = [];
var markers = [];
markers.push({
"Location": "Chicago",
"IsLocation": "Yes"
});
markers.push({
"Location": "Los Angeles",
"IsLocation": "Yes"
});
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var fieldWrapper = $("<div class='fieldwrapper' id='field" + cnt + "'/>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + cnt + "' name='TxtoptNm" + cnt + "' />");
fieldWrapper.append(fName);
fieldWrapper.append('<br />');
fieldWrapper.append('<br />');
$("#abc").append(fieldWrapper);
var newInput = [];
var newEl = document.getElementById('Txtopt' + cnt);
var txtboxId = 'Txtopt' + cnt;
newInput.push(newEl);
setupAutocomplete(autocomplete, newInput, 0, txtboxId);
cnt = cnt + 1;
} else
alert("Cant create more than 5 textbox")
}
function setupAutocomplete(autocomplete, inputs, i, txtboxId) {
autocomplete.push((txtboxId));
var idx = autocomplete.length - 1;
document.getElementById(autocomplete[idx]).addEventListener("change", function() {
alert(document.getElementById(autocomplete[idx]).value);
var autoTextbox = [{
"Location": document.getElementById(autocomplete[idx]).value,
"IsLocation": "Yes"
}]
var markerLastIndexData = [{
"Location": markers[markers.length - 1].Location,
"IsLocation": "Yes"
}]
markers[markers.length - 1] = autoTextbox;
markers[markers.length] = markerLastIndexData;
console.log(markers)
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc"></div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>
You can check in console.I am getting not proper result.
Getting output like this:
Console output coming undefine:
Expected Output are shown in my scenarios like:
marker[0]:{
Location="Chicago",
Isolcation="Yes"
}
marker[1]:{
Location="abc",
Isolcation="Yes"
}
etc......
It's happening because in the setupAutocomplete function you're assigning an Array instead of an Object to the markers Array. Just remove the []'s on the lines where you the declare the two variables that are going to be pushed to the markers array.

Search/autocomplete using JQuery from JSON file(need to get only result starting with the alphabet given)

I have created a country search when typing in the input box.
HTML is
Country<div class="holder_form"><input id="country" name="country" type="text" placeholder="Country" value="">
<ul id="country_wrapper"></ul>
Javascript is
var countries={
"1": {
"name": "Afghanistan"
},
"2": {
"name": "India"
},
"3": {
"name": "Canada"
},
"4": {
"name": "Estonia"
},
"5": {
"name": "Greece"
},
"6": {
"name": "Kenya"
},
"7": {
"name": "Liberia"
},
"8": {
"name": "Nepal"
}
}
$("#country").keyup(function (e) {
var country = $( "#country" ).val();
var len = country.length;
if(len <=0 && country!=''){
return false;
}
else if(len > 0){
var matches = [];
for (var i in countries) {
var countriesMatch = countries[i].name.toLowerCase();
if ( (countriesMatch.indexOf(country.toLowerCase()) != -1) ) {
matches.push( {'id': i, 'name': countries[i].name} );
}
}
var content='';
if ( matches.length == 0 ) {
$('#country_wrapper').css('margin-top','20');
content = '<li style="font-weight:bold;font-size: 18px;"><div class="nomatchfound">No match found</div></li>';
$('#country_wrapper').html(content).show();
return;
}
for (var i in matches) {
content += '<li style="font-weight:bold;font-size: 18px;"><a data-id="' + matches[i].id + '" class="country-select-item"><div id='+matches[i].name+' class="matchfound">'+matches[i].name+'</div></a></li>';
}
$('#country_wrapper').html(content).show();
$('.matchfound').click(function(e) {
var countryName = $(this).text();
$( "#country" ).val(countryName);
$('#country_wrapper').html('')
$('#country_wrapper').css('display','none');
});
}
});
Here is the Jsfiddle demo
It works fine... :)
But I need to show only the country name which start with the letter(alphabet) I pressed in input box
ie,
Here when I pressed key "a" it shows all country names contining letter "a". But I need to get only country names starting with "a" in the list.. How is it possible?
Thanks in advance
Use RegExp to create new regular expression
var matchMe = new RegExp('^' + country, 'i');
character ^ will search only at begining, option 'i' is "case insensitive", so no need to lowercase them before comparision
there is also "g" option for global search and "m" for multiline search
learn more about regular expressions
http://www.w3schools.com/js/js_regexp.asp
then use it in condition
if (countries[i].name.search(matchMe) > -1 )
modified code - line 37 and 40
http://jsfiddle.net/f5g0nr8h/
You are adding matches to the results via string.indexOf(), the return value is 0 if the string starts with the search pattern. Therefore you could use:
if ( (countriesMatch.indexOf(country.toLowerCase()) === 0) ) {
matches.push( {'id': i, 'name': countries[i].name} );
}

Can't change the value of an id within on function

I'd like to change the value of a <h2> with its id within a "on" function but it doesn't change.
Here's the code:
<div id="boardGame">
</div>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html("<h2>Welcome to The Game of Monkeys</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' class='stres' value='Start' onclick='getSong()'></td></tr></tbody></table")
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
$("#boardGame").html('<table class="calculatrice" id="calc"> '+
'<tbody>' +
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#boardGame").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
$("#boardGame").append('<tr>' +
'<td class="calc_td_btn">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>')
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>
And it's the value of #valueScore that doesn't want to change. I think it it a scope problem but I can't get my way around it.
I can the value of #valueScore in the console or if I put the piece of code $("#valueScore").html(score) somewhere else in my JavaScript.
EDIT : added the whole code
The problem is that you're blowing away the DOM of all the elements at line 93-106 and you're re-creating them all. So the element that you're setting the score on is being destroyed and replaced with a completely different <h2>.
Instead of destroying everything (line 82 is where you replace the html of '#boardGame') you need to use JQuery to modify the buttons that already exist to give them the names of the song list.
As an alternative, try doing this:
Give all the multiple-choice buttons a class: '.choice_button'
Put a <div id="button_wrapper"> around all the buttons so that you have something to insert the new buttons into.
Instead of replacing the HTML for '#boardGame' simply destroy all the buttons: $('#button_wrapper .choice_button').remove()
Now you can insert the new buttons using that for loop just like you're doing on line 93
Now $('#valueScore') hasn't been blown away so the score should remain.
I've modified your code to get it to where I think it's what you're after:
<div id="boardGame">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
return false;
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html(
'<h2>Welcome to The Game of Monkeys</h2>'+
'<table class="calculatrice" id="calc">' +
'<tbody>' +
'</tbody>' +
'</table>' +
'<div id="gameButtons" style="display: none;">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</div>' +
'<input type="button" class="stres" value="Start" onclick="getSong()">'
)
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
// adds the music player, of course
$('#calc tbody').html (
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
// adds the multiple choice buttons
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#calc tbody").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
// shows the score and the restart button
$('#gameButtons').show();
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>
Oh I think I see the problem. You do not need to use the .html function.
Using jQuery:
$("#valueIter").val(iter+"/10");
$("#valueScore").val(score);
The html function is used to populate an element with raw html. The difference here is that jQuery provides .val() and .text() as getters and setters for any element which equate to the javascript equivelent of
element.value = score;

Categories