French Quiz Not Working - javascript

I have made a french quiz but it is not working.
Here is the code:
<html>
<head>
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Quiz</h1>
<p id="one"></p>
<input id="aone" />
<br>
Mark It
<script>
var verbs = ["accompagner","aider","aimer","apporter","chanter","danser","coûter","écouter","étudier","fermer","jouer","laver","marcher","montrer","oublier","passer","penser","préparer","raconter","agir","bâtir","choisir","désobéir","finir","guérir","nourrir","obéir","punir","réfléchir","remplir","réussir","rougir","saisir","attendre","défendre","descendre","entendre","interrompre","perdre","rendre","répondre","rompre","vendre"];
var verb = verbs[Math.floor(Math.random() * verbs.length)];
if(verb.slice(-2) == "er") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "es";
}
if(verb.slice(-2) == "ir") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "is";
}
if(verb.slice(-2) == "re") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "s";
}
document.getElementById("one").innerHTML = verb;
document.getElementById("btn").onclick = function () {
if (document.getElementById("aone").value==newverb) { // Not Working.
alert("Correct");
}
}
</script>
</body>
</html>
I think I have traced the problem to the final if statement not being true but I don't understand why.
All help will be appreciated.

Its really unclear what you are trying to do since it is in another language.
However, your conditional is working. I added a alert() so you can see what "newverb" is equal to.
If in the input field, you add the value that was alerted, the conditional will work.
see fiddle: https://jsfiddle.net/DIRTY_SMITH/q7k2ez2L/

Related

Javascript identical if else statements behaving differently /not outputting HTML

I am new to JS and was trying to practice conditionals when I ran into this really weird problem.
Each conditional is working as intended in the sense that when the desired condition is met, the code is executed, for example, console.log() is outputting exactly what I want it to but trying to output the same to HTML is not working for some reason.
My code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
$("#test").html("Your guess was correct!");
} else if (guess > ranNumber) {
$("#test").html("Your guess was too high!");
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Now, I am using Jquery to write the HTML to the p tag but I also tried it like this:
<!DOCTYPE html>
<html>
<head>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
document.getElementById("test").innerHTML = "Your guess was correct!";
} else if (guess > ranNumber) {
document.getElementById("test").innerHTML =
"Your guess was too high!";
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Your page can't load while you're in the while loop and using prompt halts your javascript until it gets an input. Here's a link to a similar question that was asked:
https://www.reddit.com/r/webdev/comments/p8vod8/very_new_to_js_why_does_the_html_text_not_load/
A much better way which is also pretty easy is using an input field and a button. the onclick option runs your function
<input type="number" id="input">
<button onclick="guess()">Guess</button>
And your javascript can look like this
const max = 5
const ranNumber = Math.floor(Math.random() * max) + 1
console.log(ranNumber)
function guess(){
let input = document.getElementById('input').value
let text = document.getElementById('test')
if(input == ranNumber){
text.innerHTML = "You guessed it!"
}
else{
text.innerHTML = "Wrong!"
}
}
The fact that yr code does work! can be seen in the debugger,
but only that the loop runs to fast that you can't see it,
Congrats, for your use of 'const, Number(),' guess === ranNumber assignment operator given that, you say U are new to JS
So to output it to Html, you would need a little bit of adjustment!

switch from image to random image onclick with JavaScript

I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>

returning jquery alert box in function execution

i have written a javascript function and i want to return a message in the jquery alert box! currently the message is returned in a javascript alert box which seems not attractive for my program! i am unfamiliar with jquery so please help me!
my program code is as follows and is used to identify whether an uploaded file is of image format or not! if its not an image format 1 an alert box is returned with an error message!(i want to make this alert a box a jquery 1) please help me
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry a copy may be in a different file format! Formats allowed are " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
<!DOCTYPE html>
<head>
<title>jQuery Alerts</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.ui.draggable.js" type="text/javascript"></script>
<script src="jquery.alerts.js" type="text/javascript"></script>
<link href="jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" />
<!-- Example script -->
<script type="text/javascript">
$(document).ready( function() {
$("#basic_button").click( function() {
jAlert('Example of a basic alert box in jquery', 'jquery basic alert box');
});
});
</script>
</head>
<body>
<p>
<input id="basic_button" type="button" value="Show Basic Alert" />
</p>
</body>
</html>
You can download the dependency files here

Ping-Pong aka FizzBuzz test

I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.
It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value
Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!

JavaScript updating a global variable

I am currently not the most experienced in Javascript and I'm trying to learn bit by bit. Anyway... how do I update the balance variable more efficiently?
Currently I believe I am doing this wrong. Also my button does not work on click event.
Anything would be a massive help! Thank you.
// Set global variables
var name;
var balance;
var weed;
// Ask the user his name for his character
name = window.prompt("What is your name?", "Cap'n Grow");
var finalName = document.getElementById('name');
finalName.textContent = name;
// Set the balance to default
balance = 100;
var FinalBalance = document.getElementById('balance');
FinalBalance.textContent = balance;
// Set the balance of weed to default
weed = 10;
var FinalWeed = document.getElementById('gear');
FinalWeed.textContent = weed;
// Sell function
function sellGear() {
var check = window.prompt("Are you sure you want to sell 5 bags?", "Yes");
if (check === 'Yes' && weed >= 5) {
console.log("Transaction was successful!");
// Update the balance
var updBalance = document.getElementById('balance');
updBalance.textContent = balance + 150;
} else {
console.log("Failed!")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="container">
<header>
<div class="dashboard">
<div id="name"></div>
<div id="balance"></div>
<div id="gear"></div>
<div id="sell">
<button id="sellButton" onlick="sellGear()">Sell?</button>
</div>
</div>
</header>
</div>
</body>
<script src="js/global.js"></script>
</html>
Here is the solution and a suggestion:
Try to use java script code at the end of your HTML.
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="container">
<header>
<div class="dashboard">
<div id="name"></div>
<div id="balance"></div>
<div id="gear"></div>
<div id="sell">
<button id="sellButton" onclick="return sellGear();">Sell?</button>
</div>
</div>
</header>
</div>
</body>
<script src="js/global.js"></script>
</html>
<SCRIPT>
// Set global variables
var name;
var balance;
var weed;
// Ask the user his name for his character
var name = window.prompt("What is your name?", "Cap'n Grow");
var finalName = document.getElementById('name');
finalName.textContent = name;
// Set the balance to default
var balance = 100;
var FinalBalance = document.getElementById('balance');
FinalBalance.textContent = balance;
var weed = 10;
var FinalWeed = document.getElementById('gear');
FinalWeed.textContent = weed;
// Sell function
function sellGear() {
var check = window.prompt("Are you sure you want to sell 5 bags?", "Yes");
if (check === 'Yes' && weed >= 5) {
console.log("Transaction was successful!");
// Update the balance
var updBalance = document.getElementById('balance');
updBalance.textContent = balance + 150;
} else {
console.log("Failed!")
}
}
</SCRIPT>

Categories

Resources