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

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.

Related

How to compare 2 text input values?

I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.

Javascript - Play sound along with random values from an array

I am trying to make a quizz with random questions. I would like each question to be accompanied by a sound clip that plays automatically as soon as the question is shown. I would also like to have a button that makes it possible for the user to replay the sound clip. How can I achieve this, exactly?
I know how to play individual audio clips with audioClips.play();.
But how about playing audio clips from an array, "synchronized" with the questions?
This is what I have so far:
var country = ["Italy", "Spain", "Portugal", "France", "Greece", "Ireland", "Germany"];
var audioClips = ["italy.mp3", "spain.mp3", "portugal.mp3", "france.mp3", "greece.mp3", "ireland.mp3", "germany.mp3"];
var capital = ["rome", "madrid", "lisbon", "paris", "athens", "dublin", "berlin"];
var random001 = Math.floor(Math.random() * country.length);
document.getElementById("country").textContent = country[random001];
function submit001() {
var b = input001.value.toLowerCase();
var text;
if (b === capital[random001]) {
goToNextQuestion();
text = "Correct!";
} else {
text = input001.value.bold() + " is not correct!";
}
document.getElementById("input001").value = "";
document.getElementById("answer001").innerHTML = text;
}
function goToNextQuestion() {
document.getElementById("answer001").innerHTML = "";
random001 = Math.floor(Math.random() * country.length);
document.getElementById("country").innerHTML = country[random001];
document.getElementById("input001").focus();
}
<p id="message001">What is the capital of <text id="country"></text>?</p>
<input type="text" id="input001" autofocus onKeyDown="if(event.keyCode==13) submit001()">
<p id="answer001"></p>
<button onclick="playAudio()" type="button">Replay Audio</button>
With this problem you're thinking in terms of Arrays and you need to think in terms of Objects. Combine the related information into an Object and you can accomplish your goal with clear, easy-to-read code.
To make this work I had to extensively refactor your code. Here's what I came up with.
HTML
<head>
<style>
#startButton {
display: block;
}
#quiz {
display: none;
}
</style>
</head>
<body>
<div id="startButton">
<button type="button" onclick="startQuiz()">Start Quiz</button>
</div>
<div id="quiz">
<p id="message001">What is the capital of <text id="country"></text>?</p>
<input type="text" id="input001" autofocus onKeyDown="if(event.keyCode==13) checkAnswer()" value="">
<p id="answer001"></p>
<button id="replayButton" type="button" onclick="setAudio()">Replay Audio</button>
</div>
</body>
Javascript
<script>
var country = {
"Italy": {
"audio": "italy.mp3",
"capital": "rome"
},
"Spain": {
"audio": "spain.mp3",
"capital": "madrid"
},
"Portugal": {
"audio": "portugal.mp3",
"capital": "lisbon"
},
"France": {
"audio": "france.mp3",
"capital": "paris"
},
"Greece": {
"audio": "greece.mp3",
"capital": "athens"
},
"Ireland": {
"audio": "ireland.mp3",
"capital": "dublin"
},
"Germany": {
"audio": "germany.mp3",
"capital": "berlin"
}
};
var countryArray = Object.keys(country);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function nextCountryName(){
let randIndex = getRandomInt(1, countryArray.length) - 1;
return countryArray[randIndex];
};
function playAudio(file){
let playFile = new Audio(file);
playFile.play();
}
function newCountry(newCountryName) {
document.getElementById("country").textContent = newCountryName;
document.getElementById("input001").value = "";
}
function isAnswerCorrect(answer, useCountry) {
let answerId = document.getElementById("answer001");
let ans = answer.toLowerCase();
let text;
if(ans == country[useCountry].capital){
answerId.innerHTML = "Correct!";
return true;
} else {
answerId.innerHTML = ans.bold() + " is not correct!";
return false;
}
};
function setAudio(){
let thisCountry = document.getElementById("country").textContent;
let audioFile = country[thisCountry].audio;
let callStr = "playAudio(\'" + audioFile + "\')";
document.getElementById('replayButton').setAttribute('onclick', callStr);
}
function checkAnswer(){
let inputId = document.getElementById('input001');
let answer = inputId.value;
let thisCountry = document.getElementById("country").textContent;
let audioFile = country[thisCountry].audio;
let result = isAnswerCorrect(answer, thisCountry);
if(result) {
let cntryName = nextCountryName();
newCountry(cntryName);
playAudio(country[cntryName].audio);
}
};
function startQuiz(){
let startingCountry = nextCountryName();
newCountry(startingCountry);
document.getElementById('startButton').style.display = "none";
document.getElementById('quiz').style.display = "block";
playAudio(country[startingCountry].audio);
};
</script>
I converted var country, var audioClips, and var capital arrays into a single Object named var country. This way you can use country.capital or country.audio to get the value you're looking for.
According to this answer it is suggested that you set the audio file type new Audio("file_name") before calling the .play() method.
While answer002, answer003, input002, input003, etc is beyond the scope of your question this code could be easily modified accept such parameters to account for a more extensive quiz.
function playAudio() {
// if you know how to play audio then follow these step
//1. get file name from audioClips array at index randome001 like
audioClip = audioClips[random001]
// do whatever you need to do before playing audio like loading audio file or whatever
//2. play audioClip.
}`

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()">

Onclick doesn't work inside anchor element

I have problem with anchor element and onclick attribute. The idea is that I have main function loadTableWithFilters that gets values from the pet data base and then draws a table with pets. The other functions are intended to change filters and call loadTableWithFilters function again. The problem that I have is with function calls from my html file.
This simply doesn't work
<li><a onclick="filterAllPets()">All Pets</a></li>
It gives me this error
Uncaught ReferenceError: filterAllPets is not defined
at HTMLAnchorElement.onclick
What I tried to do to solve this problem:
moved my <script> tags before </body>
changed function loadTableWithFilters ( petData ) to var loadTableWithFilters = function ( petData )
I know that I can give id to anchors and write some snippets like #id.onclick = function() but that's not the intention. I really don't understand why it doesn't work. Please explain it.
Code files
main.html
<!doctype html>
<html>
<head>
<title>~ Purfect Pets ~</title>
<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/assignment4-theme.css" />
<link rel="stylesheet" href="css/a4-main.css" />
<!-- development css -->
<style>
table, td, th {
border: 1px solid black;
}
</style>
</head>
<body>
<header>
<div class="center">
<h1 class="app-title">
~ Purfect Pets ~
</h1>
</div>
</header>
<nav>
<div class="center">
<ul>
<li><a onclick="filterAllPets()">All Pets</a></li>
<li><span>|</span></li>
<li><a onclick="filterDog()">Dogs</a></li>
<li><a onclick="filterCat()">Cats</a></li>
<li><a onclick="filterBird()">Birds</a></li>
<li><span>|</span></li>
<li><a onclick="filter_zero_1()">< 1 year</a></li>
<li><a onclick="filter_1_3()">1 - 3 years</a></li>
<li><a onclick="filter_4_plus()">4+ years</a></li>
</ul>
</div>
</nav>
<section class="main center">
<table class="main-table-top">
<tbody>
<tr>
<th>Photo</th>
<th>Description</th>
</tr>
</tbody>
</table>
<div class="main-table-container">
<table class="main-table">
<tbody id="main-table-body">
<!-- tester -->
</tbody>
</table>
</div>
</section>
<footer>
<div class="center">
© 2017 Anton Elistratov
</div>
</footer>
<script src="js/data.js"></script>
<script src="js/a4-main.js"></script>
</body>
</html>
a4-main.js
//a4-main.js
window.onload = function() {
var filterType = ""; // sets the filter type to "" (will later be dog, cat or bird)
var filterAgeMin = 0; // sets the filter age min to 0 (for no minimum age filter)
var filterAgeMax = Number.MAX_VALUE; // sets the filter age max to the largest number possible (for no maximum age filter)
//
var loadTableWithFilters = function ( petData ){
var htmlRow = document.querySelector('#main-table-body');//getting my placeholder
htmlRow.innerHTML = "";//clearing
var i;//for loop increment
for (i = 0; i < petData.length; i++){
//$('#main-table-body tr td').append('<img src="' + petData[i].image.src + '"/>');
//getting image
if (petData[i].type === filterType || filterType === "" && petData[i].age >= filterAgeMin && petData[i].age <= filterAgeMax){
var image = document.createElement('img');
image.src = petData[i].image.src;
image.alt = petData[i].image.alt;
image.height = petData[i].image.height;
image.width = petData[i].image.width;
//getting name
var name = document.createElement('h4');
name.textContent = petData[i].name;
//getting description
var description = document.createElement('p');
description.innerHTML = petData[i].description;
//getting age
var age = document.createElement('span');
age.textContent = petData[i].age;
var type = petData[i].type;
//append('<li><img src="' + imgSrc[i] + '"/></li>');
var fullRow = document.createElement('tr');
var colLeft = document.createElement('td');
var colRight = document.createElement('td');
colLeft.appendChild(image);
colRight.appendChild(name);
colRight.appendChild(description);
colRight.appendChild(age);
//table assembly
fullRow.appendChild(colLeft);
fullRow.append(colRight);
htmlRow.appendChild(fullRow);
}
}//for (i = 0; i < petData.length; i++)
}
/* My filters */
//filters dogs
var filterDog = function () {
filterType = "dog";
loadTableWithFilters( petData );
}
//filters cats
var filterCat = function () {
filterType = "cat";
loadTableWithFilters( petData );
}
var filterBird = function () {
filterType = "bird";
loadTableWithFilters( petData );
}
//must be invoked when the user clicks "< 1 year"
var filter_zero_1 = function (){
filterAgeMin = 0;
filterAgeMax = 1;
loadTableWithFilters( petData );
}
//must be invoked when the user clicks "1 - 3 years"
var filter_1_3 = function (){
filterAgeMin = 1;
filterAgeMax = 3;
loadTableWithFilters( petData );
}
//must be invoked when the user clicks "4+ years"
var filter_4_plus = function () {
filterAgeMin = 4;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters( petData );
}
/*This function simply sets the global filterType variable to "", the filterAgeMin variable to 0, the filterAgeMax variable to Number.MAX_VALUE and invokes the loadTableWithFilters function again to refresh the table. This function must be invoked when the user clicks "All Pets"*/
var filterAllPets = function () {
filterType = "";
filterAgeMin = 0;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters( petData );
}
//function call
loadTableWithFilters( petData );
};//window.onload = function()
data.js
//data.js
var petData = [
{
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Bella.jpg", alt: "Bella", width: 120, height: 160 },
name: "Bella",
age: 0.5,
description: "<span>Bella</span> is a bright young pup who loves being around other dogs and doesn't mind the odd cat.<br />Her <span>favourite treat</span> is <span>bacon</span> - anything <span>bacon</span>.",
type: "dog"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Buddy.jpg", alt: "Buddy", width: 120, height: 160 },
name: "Buddy",
age: 4,
description: "One of the most friendly dogs currently staying with us is <span>Buddy</span>.<br />He's a little older but has a <span>lot of love</span> to give.<br />His favourite activity is cuddling up and <span>watching a movie</span> with is owner.",
type: "dog"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Charlie.jpg", alt: "Charlie", width: 120, height: 160 },
name: "Charlie",
age: 3,
description: "<span>Charlie</span> loves <span>spending time outdoors</span>. <br />He will chase anything that moves and will spend all day <span>playing fetch</span> in the park. <br />His favourite treat to eat is actually <span>broccoli</span> - crazy I know, but he loves it.",
type: "dog"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Jasper.jpg", alt: "Jasper", width: 120, height: 160 },
name: "Jasper",
age: 2,
description: "<span>Jasper</span> is only 2 years (and 3 months) old, but he's already one of the smartest pups we've seen.<br /> He will recognize his <span>toys by name</span> and will always put them back in the toy box when asked.<br />He's the only dog we've seen that <span>tidies up after himself!</span>.",
type: "dog"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Max.jpg", alt: "Max", width: 120, height: 160 },
name: "Max",
age: 5,
description: "Our little <span>Max</span> is always happy.<br />He loves to spend his time outdoors <span>playing fetch</span> and <span>going for jogs</span>.<br /> His favourite treats are <span>hot dogs</span> - any variety will do, but he loves Schneiders <span>Red Hots</span> the best.",
type: "dog"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/David.jpg", alt: "David", width: 120, height: 160 },
name: "David",
age: 0.5,
description: "<span>David</span> is our smallest kitten at only <span>6 months old</span>! <br />His favourite thing right now is <span>chasing his tail</span> and playing with <span>packing peanuts</span>.<br />He is full of love and will make a welcome addition to any home.",
type: "cat"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Simba.jpg", alt: "Simba", width: 120, height: 160 },
name: "Simba",
age: 5,
description: "One of our oldest cats is <span>Simba</span>.<br /> He's over chasing things and is just looking for a nice place to <span>cuddle</span> - usually somebody's lap.<br /> He loves <span>Temptations</span> (any variety) and will <span>come running</span> from anywhere in the house if he suspects treats are on the way.",
type: "cat"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Sparky.jpg", alt: "Sparky", width: 120, height: 160 },
name: "Sparky",
age: 2,
description: "<span>Sparky</span> is a very wild cat, but he's a <span>ton of fun</span>.<br />He would happily spend his days chasing <span>bugs</span> or <span>squirrels</span> outside or <span>playing with you</span> inside!<br /> His favourite treat is <span>cottage cheese</span> and will eat it straight from the container if you let him.",
type: "cat"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Whiffles.jpg", alt: "Whiffles", width: 120, height: 160 },
name: "Whiffles",
age: 3,
description: "<span>Whiffles</span> is our first <span>hypoallergenic</span> cat.<br />She is very mellow and extremely friendly, making her the perfect indoor cat.<br />Her favourite treat is <span>Tuna</span> straight from the can - any variety.",
type: "cat"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Widget.jpg", alt: "Widget", width: 120, height: 160 },
name: "Widget",
age: 1.5,
description: "One of our <span>youngest</span> cats is <span>Widget</span>. <br /> He's only 18 months old and still loves to run and jump and <span>chase his toys</span>.<br />His favourite food is <span>Salmon</span>, but he will always come running for any variety of <span>cat treats</span> (i.e. Temptations, Greenies, etc). ",
type: "cat"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Augustus.jpg", alt: "Augustus", width: 120, height: 160 },
name: "Augustus",
age: 1.5,
description: "<span>Augustus</span> has been with us for just over <span>4 months</span>, and already we can see that he's <span>very friendly</span>.<br /> He will <span>chirp</span> and <span>chatter</span> whenever somebody enters the room. ",
type: "bird"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Joanna.jpg", alt: "Joanna", width: 120, height: 160 },
name: "Joanna",
age: 0.5,
description: "One of our youngest birds is <span>Joanna</span>. She is only 6 months old, but is very active.<br /> She loves <span>flying outside</span> of her cage, but will never go far. Like all birds her age, she loves playing with the “<span>bird in the mirror</span>”.",
type: "bird"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Jonathan.jpg", alt: "Jonathan", width: 120, height: 160 },
name: "Jonathan",
age: 3,
description: "<span>Jonathan</span> is one of our older birds, but is still very friendly and loves to <span>chirp and sing</span> in the morning.<br /> He loves taking <span>baths</span>, so as long as there's a <span>water bowl</span> in his cage, he'll be happy all day.",
type: "bird"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Sammy.jpg", alt: "Sammy", width: 120, height: 160 },
name: "Sammy",
age: 2.5,
description: "<span>Sammy</span> is one of our older birds, but he's also the <span>smartest</span>. He is always trying to <span>mimic</span> whatever sounds are around him. He is also a very active bird, so be sure you are able to interact with him <span>multiple</span> times a day.<br />His favourite thing is when you <span>scratch</span> under his chin. ",
type: "bird"
}, {
image: { src: "https://scs.senecac.on.ca/~patrick.crawford/shared/winter-2017/web222/assignment4/pets/Suzette.jpg", alt: "Suzette", width: 120, height: 160 },
name: "Suzette",
age: 4,
description: "The oldest bird currently staying with us is <span>Suzette</span>. She's extremely <span>cuddly</span> and loves landing on people's glasses, collars, hats, or whatever she can get her little claws on, as long as she can be close. She's a great <span>companion</span> for anyone looking for a bird that will interact with them and remain <span>close by</span>.",
type: "bird"
}
];
Just remove it from window.load and it will work.
From this:
window.onload = function() {
var filterType = ""; // sets the filter type to "" (will later be dog, cat or bird)
var filterAgeMin = 0; // sets the filter age min to 0 (for no minimum age filter)
var filterAgeMax = Number.MAX_VALUE; // sets the filter age max to the largest number possible (for no maximum age filter)
//
var loadTableWithFilters = function(petData) {
var htmlRow = document.querySelector('#main-table-body'); //getting my placeholder
htmlRow.innerHTML = ""; //clearing
var i; //for loop increment
for (i = 0; i < petData.length; i++) {
//$('#main-table-body tr td').append('<img src="' + petData[i].image.src + '"/>');
//getting image
if (petData[i].type === filterType || filterType === "" && petData[i].age >= filterAgeMin && petData[i].age <= filterAgeMax) {
var image = document.createElement('img');
image.src = petData[i].image.src;
image.alt = petData[i].image.alt;
image.height = petData[i].image.height;
image.width = petData[i].image.width;
//getting name
var name = document.createElement('h4');
name.textContent = petData[i].name;
//getting description
var description = document.createElement('p');
description.innerHTML = petData[i].description;
//getting age
var age = document.createElement('span');
age.textContent = petData[i].age;
var type = petData[i].type;
//append('<li><img src="' + imgSrc[i] + '"/></li>');
var fullRow = document.createElement('tr');
var colLeft = document.createElement('td');
var colRight = document.createElement('td');
colLeft.appendChild(image);
colRight.appendChild(name);
colRight.appendChild(description);
colRight.appendChild(age);
//table assembly
fullRow.appendChild(colLeft);
fullRow.append(colRight);
htmlRow.appendChild(fullRow);
}
} //for (i = 0; i < petData.length; i++)
}
/* My filters */
//filters dogs
var filterDog = function() {
filterType = "dog";
loadTableWithFilters(petData);
}
//filters cats
var filterCat = function() {
filterType = "cat";
loadTableWithFilters(petData);
}
var filterBird = function() {
filterType = "bird";
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "< 1 year"
var filter_zero_1 = function() {
filterAgeMin = 0;
filterAgeMax = 1;
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "1 - 3 years"
var filter_1_3 = function() {
filterAgeMin = 1;
filterAgeMax = 3;
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "4+ years"
var filter_4_plus = function() {
filterAgeMin = 4;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters(petData);
}
/*This function simply sets the global filterType variable to "", the filterAgeMin variable to 0, the filterAgeMax variable to Number.MAX_VALUE and invokes the loadTableWithFilters function again to refresh the table. This function must be invoked when the user clicks "All Pets"*/
var filterAllPets = function() {
filterType = "";
filterAgeMin = 0;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters(petData);
}
//function call
loadTableWithFilters(petData);
}; //window.onload = function()
to this:
var filterType = ""; // sets the filter type to "" (will later be dog, cat or bird)
var filterAgeMin = 0; // sets the filter age min to 0 (for no minimum age filter)
var filterAgeMax = Number.MAX_VALUE; // sets the filter age max to the largest number possible (for no maximum age filter)
//
var loadTableWithFilters = function(petData) {
var htmlRow = document.querySelector('#main-table-body'); //getting my placeholder
htmlRow.innerHTML = ""; //clearing
var i; //for loop increment
for (i = 0; i < petData.length; i++) {
//$('#main-table-body tr td').append('<img src="' + petData[i].image.src + '"/>');
//getting image
if (petData[i].type === filterType || filterType === "" && petData[i].age >= filterAgeMin && petData[i].age <= filterAgeMax) {
var image = document.createElement('img');
image.src = petData[i].image.src;
image.alt = petData[i].image.alt;
image.height = petData[i].image.height;
image.width = petData[i].image.width;
//getting name
var name = document.createElement('h4');
name.textContent = petData[i].name;
//getting description
var description = document.createElement('p');
description.innerHTML = petData[i].description;
//getting age
var age = document.createElement('span');
age.textContent = petData[i].age;
var type = petData[i].type;
//append('<li><img src="' + imgSrc[i] + '"/></li>');
var fullRow = document.createElement('tr');
var colLeft = document.createElement('td');
var colRight = document.createElement('td');
colLeft.appendChild(image);
colRight.appendChild(name);
colRight.appendChild(description);
colRight.appendChild(age);
//table assembly
fullRow.appendChild(colLeft);
fullRow.append(colRight);
htmlRow.appendChild(fullRow);
}
} //for (i = 0; i < petData.length; i++)
}
/* My filters */
//filters dogs
var filterDog = function() {
filterType = "dog";
loadTableWithFilters(petData);
}
//filters cats
var filterCat = function() {
filterType = "cat";
loadTableWithFilters(petData);
}
var filterBird = function() {
filterType = "bird";
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "< 1 year"
var filter_zero_1 = function() {
filterAgeMin = 0;
filterAgeMax = 1;
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "1 - 3 years"
var filter_1_3 = function() {
filterAgeMin = 1;
filterAgeMax = 3;
loadTableWithFilters(petData);
}
//must be invoked when the user clicks "4+ years"
var filter_4_plus = function() {
filterAgeMin = 4;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters(petData);
}
/*This function simply sets the global filterType variable to "", the filterAgeMin variable to 0, the filterAgeMax variable to Number.MAX_VALUE and invokes the loadTableWithFilters function again to refresh the table. This function must be invoked when the user clicks "All Pets"*/
var filterAllPets = function() {
filterType = "";
filterAgeMin = 0;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters(petData);
}
//function call
loadTableWithFilters(petData);

Js won't work if I want to add more code

I don't know why my code will stop work if i add a if statment to my last function var checkAnswer = function(). If i delete the statment the code will work again fine. What's the problem with it? It's kinda wierd and I don't get it.
Array.prototype.random = function(length) {
return this[Math.floor(Math.random() * length)];
};
var country = [{
name: "romaniei",
capital: "bucuresti"
}, {
name: "bulgariei",
capital: "sofia"
}],
questions = [
"What is the capital of ",
" is the capital of what country?"
]
document.querySelector('input').onclick = function() {
var q,
chosen_country = country.random(country.length),
chosen_question = questions.random(questions.length);
if (chosen_question == questions[0]) {
q = chosen_question + chosen_country.name + "?";
} else if (chosen_question == questions[1]) {
q = chosen_country.capital + chosen_question;
}
document.querySelector('#que').innerHTML = q;
}
var checkAnswer = function() {
var answer = document.myform.answ.value;
if () {}
}
<form name="myform">
<input type="button" value="Generate question">
<div id="que">Intrebare:</div>
<input type="text" id="answ">
<input type="button" value="ok">
</form>
if () {} isn't a valid if statement - the condition body has to be an expression.
Source: ECMAScript 5 spec
For example, any of these are valid:
if (true) {}
if (1 < 2) {}
if("") {}

Categories