Making a quiz in html/javascript alerts not working - javascript

Making a simple multiple choice, short answer and multiple response quiz on peanut butter and jelly :). What I'm trying to do is when the user clicks the "submit" button it shows the number of correct or incorrect answers. Also, next to the question show if the choice they chose was correct or incorrect, for example on the multiple choice question, if they select the right answer(jelly) then it would say "correct!" next to that option. Right now when I click submit nothing is happening, not sure why, I thought it would pop up an alert with the amount correct but nothing happens. I'm sure I'm missing something very simple but for some reason it hasn't popped out for me so any help will be greatly appreciated.
thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to make a proper Peanut Butter and Jelly
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src = "scripts/main.js"></script>
</head>
<body>
<header>
</header>
<main>
<form id = "quiz" name = "quiz">
<p>what item do you use to spread peanut butter on the bread?</p>
<input id = "textbox" type = "text" name = "question1">
<p>what is one ingrediant of peanut butter and jelly sandwich?</p>
<input type = "radio" id = "mc" name = "question2" value = "cheese"> cheese <br>
<input type = "radio" id = "mc" name = "question2" value = "bacon"> bacon <br>
<input type = "radio" id = "mc" name = "question2" value = "jelly"> jelly <br>
<p>which of the following are correct ingredients required to make a Peanut Butter and Jelly sandwich?</p>
<input type = "checkbox" id = "mc" name = "question2" value = "bread"> bread <br>
<input type = "checkbox" id = "mc" name = "question2" value = "cheese"> cheese <br>
<input type = "checkbox" id = "mc" name = "question2" value = "peanut butter"> peanut butter <br>
<input type = "checkbox" id = "mc" name = "question2" value = "jelly"> jelly <br>
<input type = "checkbox" id = "mc" name = "question2" value = "toothpaste"> toothpaste <br>
<br>
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check():">
<br>
</form>
</main>
<footer>
</footer>
</body>
javascript code
function src(){
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
var incorrect = 0;
if (question1 == "knife")
{
alert("correct!");
correct++;
}
else{
alert("incorrect");
incorrect++;
}
if(question2 == "jelly")
{
alert("correct!");
correct++;
}
else{
alert("incorrect");
incorrect++;
}
if(question3 == "bread"||"jelly"||"peanut butter"){
alert("correct!");
correct++
}
else{
alert("incorrect");
incorrect;
}
alert(correct);
}

To begin with, you seem like you are familiar with other programming languages. such as C# or java for example but you don't know the basics of DOM manipulation. So bear with me now till I explain it to you in brief details.
first of all, the DOM is the (Document Object Model) it is basically the image created using your mark up language (HTML). basically this is the things displayed on the browser and manipulated by javascript. like the buttons on this page or the text box I'm typing right now or the navigation bar above.
So, a quick recap the DOM is created using HTML and manipulated using javascript.
As the DOM is created by the html you won't be able to manipulate it until it till the html is loaded. you adding the script tag on the top of the html page means you run the manipulating things that are not there. So, you have to add the script tag at the end of the html page before the body closing tag.
<script src = "scripts/main.js"></script>
</body>
Now, when you want to manipulate an element you have to store it in a variable and the way to do this is by using a selector.
You have three options but just to save time I won't state the 3 I will state the best and most commonly used one. you can google the others but I don't think it is worth it though.
so if you know css you select a component wether by its name or id or class.
there is something in javascript called query selector and it is used like this.
var x = document.queryselector('css-selector');
Instead of the css-selector part you add a css selector.
for example if the element has a class of 'hero'. you will replace css-selector with .hero or if it has the id of 'hero' you will replace the css-selector with #id.
Then you should use the variable name to manipulate the element.
here are more useful links that you can check out.
JavaScript

Try removing the colon : on the submit button onclick
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check():">
Change this to
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check()">

Right now, your submit onclick handler is check(). But you have no function called check(). Did you mean to do
onclick = "src()">
instead?
Do note that you should put all of your Javascript in the Javascript - it's bad practice to put handlers in the HTML, it'll only make things harder for you in the long run. Strongly consider using addEventListener.

Related

Load whole page before javascript runs

I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}
You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>
You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.

Creating a quiz page using Javascript

I was trying to create a simple quiz page using Javascript. Else it went well, but after I run this code in browser, on pressing submit button the DOM text appeared in paragraph(through Script) disappears just after a flash. I had expected the text to remain on screen until the next action. Please help me troubleshoot this problem.
Thank you
Code
<!DOCTYPE HTML>
<html>
<head>
<title>
Quiz
</title>
<script type = "text/Javascript">
function checkAnswers()
{
var myQuiz = document.getElementById( "myQuiz" );
if ( myQuiz.elements[ 2 ].checked )
document.getElementById("demo").innerHTML = "Congrats, Thats the Right answer";
else
document.getElementById("demo").innerHTML = "Woops!! The Correct answer is 'Mouse'.<br>Click 'Next' to Proceed";
}
</script>
</head>
<body>
<br><br><br><br><br><br>
<form id = "myQuiz" onsubmit = "checkAnswers()" action = "">
Which among the following is readily found in computers ?
<br><br><br>
<input type = "radio" name = "radiobutton" value = "A" /><label> Zebra</label>
<input type = "radio" name = "radiobutton" value = "B" /><label> Girrafe</label>
<br><br> <input type = "radio" name = "radiobutton" value = "C" /><label>Mouse</label>
<input type = "radio" name = "radiobutton" value = "D" /><label>Mosquito</label>
</div><br><input type = "submit" name = "submit" value = "Submit" />
<br>
<p id = "demo" "> </p>
</form>
</body>
</html>
Make the following changes:
HTML
<form id = "myQuiz" onsubmit = "checkAnswers(event)" action = "">
JS
function checkAnswers(event) {
event.preventDefault();
...
}
preventDefault cancels the form submit event which is causing the page to reload and your text to disappear.
DEMO
Just return "false" inside the onSubmit parameter, like this:
<form id = "myQuiz" onsubmit = "return false" action = "">
And invoke the checkAnswers() function when someone clicks the button;
<input type = "submit" name = "submit" value = "Submit" onclick="checkAnswers()" />

How can I run a JavaScript function by taking user input & using a button?

<!doctype html>
<html>
<head>
<title> Daily Recommended Exercise </title>
</head>
<body>
<h2>Your Daily Exercise Schedule</h2>
<p>Please select your age group:</p>
<form>
0 - 5: <input type = "radio" name = "PickAge" value = "Age1">
<br/>
6 - 17: <input type = "radio" name = "PickAge" value = "Age2">
<br/>
18 - 64: <input type = "radio" name = "PickAge" value = "Age3">
<br/>
65 - 150: <input type = "radio" name = "PickAge" value = "Age4">
<br/>
<input type="button" onclick = "exerciseRecommend();" value = "Enter"></input>
</form>
<script type = "text/javascript">
function exerciseRecommend()
{
var age = document.getElementsByName("PickAge");
if (age=="Age1")
{
alert("Physical activity in infants and young children is necessary for healthy growth and development. There are no guidelines for children at this age though regular physical activity is recommended.");
}
else if (age=="Age2")
{
alert("At this age you should do 60 minutes or more of physical activity each day. This includes, aerobic endurance and strength exercises.");
}
else if (age=="Age3")
{
alert("At this age you should be doing two hours and thirty minutes or more of moderate aerobic endurance and strength exercises activity every week OR one hour fifteen minutes of intense aerobic endurance and strength exercises activity OR a mix of the two.");
}
else if (age=="Age4")
{
alert("At this age you should be exercising 2-3 hours a week. It is recommended that you should be doing mild endurance and strength activities.");
}
}
</script>
</body>
</html>
What is wrong with this code? Whenever I press the button nothing happens!! I have tried again and again but for some reason it is not finding the user input and outputting any alert values! Please help!
Shashank is correct that best practice is to attach the event listener through JS itself, but in your case I'll assume that you're learning the language and just want to know what's up and how it works.
So, let's take a look at your age variable. If you console.log(age) after you define it, it will return a Node list of all of the elements with the name "PickAge". What you want is a specific one of those, the checked one.
// Get a list of all the select-able ages
var allAges = document.getElementsByName("PickAge");
// Define a variable that will hold our selected age
var age;
// Iterate through all of the select-able ages
for (i = 0; i < allAges.length; i++) {
// If the selected age is checked, set it to the "age" variable
if (allAges[i].checked === true) {
// We grab only the value here because that's what you check later
age = allAges[i].value;
}
}
That should give you the correct result that will work with your if < alert. You might want to add an else statement at the end in case the user doesn't select any age, though.
Just to make sure you know, this isn't best practice, efficient, or the best way of doing this. This is just a quick example to help you understand the process a bit to help you get the basis for the language.

can i change html content using innerhtml in javascript without using a function?

The most basic example, where say I got a variable called name. What I want to do is to put the value of my tag paragraph to the name variable.
That is, I want the value of name change in html as soon as it is changed in JavaScript.
Btw, I created a refresh name method, which works perfectly, but I need a better alternative.
<html>
<head></head>
<body>
<script>
var droid = new Android();
var name = "Player";
function getName() {
name = prompt("Enter Name");
}
function putName() {
var elm = document.getElementById("ntag");
elm.innerHTML = name;
}
</script>
<p id="ntag"></p>
<input type="button" onclick="putName();" value="Refresh Name"/>
<input type="button" onclick="getName();" value="Change Name"/>
<br>
<input type="button" onclick="droid.dismiss();" value="Exit"/>
</body>
</html>
As I understand from you question, you want to minimize the number of buttons and event-handlers.
You are currently using two buttons to prompt for input and change the content. You can get rid of your putName function and the associated button for that and change the content within the first one itself.
You should ideally use innerText instead of innerHTML in this case.
You code will somewhat look like this snippet:
Snippet:
function getName() {
name = prompt("Enter Name");
document.getElementById("ntag").innerText = name;
}
<p id="ntag"></p>
<input type="button" onclick="getName();" value="Change Name"/>

Editing html input element from javascript bugs out

I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/

Categories