How can i grab the next object from an array of divs? - javascript

I am trying to cycle through a list of Div's that have all of my trivia questions inside. I know how to cycle through all of them with an iterator but i just want to know how to grab one Div, run some code, then cycle to the next object in the array after the user has clicked submit, then run the same code etc. I also have each div hidden so they can only see one Div at a time until they are done with the previous question. Very new to Java Script and trying to learn as fast as i can, any tips would greatly be appreciated
<div class="row">
<div class="col-12 questions">
<form name="quiz" onsubmit="return false">
<div class="q1">
<h1>The 'Mountain' is the nickname for which character?</h1>
<input type="radio" name="q" value="wrong" id="q1a">a. Gerold Clegane
<br>
<input type="radio" name="q" value="wrong" id="q1b">b. Sandor clegane
<br>
<input type="radio" name="q" value="wrong" id="q1c">c. Oberyn Martell
<br>
<input type="radio" name="q" value="correct" id="q1d">d. Gregor Clegane
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q2">
<h2>Who is the youngest child of Lord Tywin Lannister?</h2>
<input type="radio" name="q" value="correct" id="q2a">a. Tyrion Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2b">b. Jaime Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2c">c. Cersei Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2d">d. Jon Snow
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q3">
<h3>Who is the King of the North?</h3>
<input type="radio" name="q" value="wrong" id="q3a">a. Bran Stark
<br>
<input type="radio" name="q" value="correct" id="q3b">b. Jon Snow
<br>
<input type="radio" name="q" value="wrong" id="q3c">c. Tommen Baratheon
<br>
<input type="radio" name="q" value="wrong" id="q3d">d. LittleFinger
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q4">
<h4>Who is the head of house Stark?</h4>
<input type="radio" name="q" value="wrong" id="q4a">a. Tyrion Lannister
<br>
<input type="radio" name="q" value="wrong" id="q4b">b. Jon Snow
<br>
<input type="radio" name="q" value="wrong" id="q4c">c. Bran Stark
<br>
<input type="radio" name="q" value="correct" id="q4d">d. Ned Stark
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q5">
<h5>Which persons are the 'Night's Watch' trying to stop by using a giant wall of ice?</h5>
<input type="radio" name="q" value="correct" id="q5a">a. White Walkers
<br>
<input type="radio" name="q" value="wrong" id="q5b">b. Wildings
<br>
<input type="radio" name="q" value="wrong" id="q5c">c. Mother of Dragons
<br>
<input type="radio" name="q" value="wrong" id="q5d">d. Night walkers
<br>
<button class="submit" type="submit">Submit</button>
</div>
</form>
Here is my Javascript
$(document).ready(function () {
console.log("ready!");
var question1 = $('.q1');
var question2 = $('.q2');
var question3 = $('.q3');
var question4 = $('.q4');
var question5 = $('.q5');
var correctAnswers = 0;
var wrongAnswers = 0;
var gameArr = [question1, question2, question3, question4, question5];
function nextGame() {
for (i=0;i<gameArr.length;i++){
//i dont want it to grab every object all at the same time
}
}
nextGame();
console.log(nextGame());
//My startGame button
$('.b1').on("click", function () {
console.log(gameArr[0]);
gameArr[0].show();
});
//Setting up audio for the start screen, make it loop so it never stops running
var audio1 = new Audio("assets/music/startMusic.mp3");
audio1.addEventListener('ended', function () {
this.currentTime = 0;
this.play();
}, false);
audio1.play();
//code to make my quiz responsive
function game() {
var answer = $("input[name='q']:checked").val();
if (answer === "correct") {
alert("Correct!");
correctAnswers = correctAnswers + 1
} else {
wrongAnswers = wrongAnswers + 1
alert("Wrong!");
}
}
//timer
function countdown() {
seconds = 60;
$('#timer').html('<h6>Time Remaining: ' + seconds + '</h6>');
time = setInterval(showCountdown, 1000);
}
function showCountdown() {
seconds--;
$('#timer').html('<h3>Time Remaining: ' + seconds + '</h3>');
if (seconds < 1) {
clearInterval(time);
}
}
//submit your answer
$('.submit').on("click", function () {
//nextGame();
game();
console.log(gameArr);
});

You have to remember the last position.
So you have a variable, call it lastGame or something. This will be a variable at the same level as correctAnswers etc. Start with zero.
Whenever you want to navigate to the next gate, increment this and do a gameArr[lastGame].show();.
Example:
var correctAnswers = 0;
var wrongAnswers = 0;
var gameArr = [question1, question2, question3, question4, question5];
var lastGame = 0;
function nextGame() {
gameArr[lastGame].show();
lastGame++;
}
And on timeout you call nextGame()

make a global iterator increase its value every time the user hits the answer , hide the old div display the new Div
something like this
var question1 = $('.q1');
var question2 = $('.q2');
var question3 = $('.q3');
var question4 = $('.q4');
var question5 = $('.q5');
var correctAnswers = 0;
var wrongAnswers = 0;
var currentIndex = 0;
var gameArr = [question1, question2, question3, question4, question5];
then after the form is submitted
$('.submit').on("click", function () {
//nextGame();
game();
if(currentIndex < (gameArr.length -1 ))
{
// I am using the hide callback which is fired by jQUery after the object is completely hidden
gameArr[currentIndex].hide(function(){
currentIndex++;
gameArr[currentIndex].show();
});
}
});

First off, you should never have more than one button of type submit per form. Move the submit button to just before the form's end tag.
You don't need variables for every question. With your jquery (haven't used jquery in awhile I'm all react now) you should be able to select your questions like this
var questions = $('form div')
Then you will need a current question variable. Maybe have all the divs with a hidden class. When the current question is selected remove that hidden class from the current div.
when the user submits the form you can check if they are at the end of the array of questions if not increment the current question and show the div for the next question. You could hide the previous question or keep it visible (up to you).

Related

Disable remaining checkboxes after checking some of them in JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to disable the checkboxes when a limit of checked checkboxes have reached. I have made a function in JavaScript in which on check of two boxes the other two become disable and the value of the checked boxes comes in id="order2". But this function is not at all working.
<!DOCTYPE html>
<html>
<body>
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
<script>
function myFunction2() {
var coffee = document.querySelectorAll("[name = coffee]"); // To get arrays by Attribute in query selector use [] to get arrays of the same attribute. We can also use ("input[type = checkbox]") to get arrays.
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
txt = txt + coffee[i].value + ", ";
document.getElementById("order2").value = "You ordered a coffee with: " + txt.slice(0, -2);
}
else if (coffee.length === 2) {
coffee[i].setAttribute("style", "pointer-events: none; opacity: 0.5");
document.getElementById("order3").value = "Boxes left uncheck " + i;
}
}
}
</script>
</body>
</html>
Make two loops. First figure out the total number of checkboxes that are checked - this will tell you whether you need to disable unchecked checkboxes. On the second loop, if a checkbox is checked, add its value to an array. Otherwise, the checkbox is unchecked; if at least 2 checkboxes are checked (identified by the previous loop), disable it.
If the user de-selects an option after hitting the limit of 2, also loop through the checkboxes and enable them all.
function myFunction2() {
const checkboxes = [...document.querySelectorAll("[name = coffee]")];
const boxesChecked = checkboxes.reduce((a, b) => a + b.checked, 0);
document.getElementById("order3").value = "Options left to choose:" + (2 - boxesChecked);
let addedCost = 0;
for (const checkbox of checkboxes) checkbox.disabled = false;
for (const checkbox of checkboxes) {
if (checkbox.checked) addedCost += Number(checkbox.value);
else if (boxesChecked === 2) checkbox.disabled = true;
}
document.getElementById("order2").value = "Costs: " + addedCost;
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
Try to available mixing HTML with JavaScript using onclick. The proper way is with event listeners, for example:
const myCheckboxes = document.querySelectorAll('input[type=checkbox]');
const myReset = document.querySelector('input[type=reset]');
myCheckboxes.forEach(checkbox => checkbox.addEventListener('click', checkCheckboxes));
myReset.addEventListener('click', resetCheckboxes);
function checkCheckboxes() {
let checked = document.querySelectorAll('input:checked');
if (checked.length >= 2) {
myCheckboxes.forEach(checkbox => checkbox.disabled = true);
}
}
function resetCheckboxes() {
myCheckboxes.forEach(checkbox => checkbox.disabled = false);
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" value="100">With cream<br>
<input type="checkbox" name="coffee" value="150">With sugar<br>
<input type="checkbox" name="coffee" value="200">With milk<br>
<input type="checkbox" name="coffee" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
You can evaluate how many are checked when they are clicked and disable the others. Note: the better way to handle this is to use classes and toggle the class.
'use strict';
document.addEventListener('click', function(e) {
if (e.target.type == 'checkbox')
myFunction2(e);
})
function myFunction2(e) {
const coffee = document.querySelectorAll('[name=coffee]');
const checked = document.querySelectorAll(':checked');
const order2 = document.querySelector('#order2');
const order3 = document.querySelector('#order3');
order2.value = checked.length
? "You ordered a coffee with: " + [...checked].map(cb => cb.value).join(', ')
: ''
if (checked.length === 2 && e.target.checked) {
coffee.forEach(cb => {
if (!cb.checked)
cb.disabled = true
});
order3.value = "Boxes left unchecked: " + (coffee.length - checked.length);
return false;
}
else
coffee.forEach(cb=>cb.disabled=false)
order3.value = "Boxes left unchecked: " + (coffee.length - checked.length);
}
input {
display: block;
}
label {
display: block;
}
label>input {
display: inline-block;
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<label><input type="checkbox" name="coffee" value="100">With cream</label>
<label><input type="checkbox" name="coffee" value="150">With sugar</label>
<label><input type="checkbox" name="coffee" value="200">With milk</label>
<label><input type="checkbox" name="coffee" value="250">With tea</label>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>

change label text of all radio button in quiz as red and green

Below is the code of a sample radio button quiz where multiple radio buttons are provided. Correct answers and wrong answers are defined in the code. User may check any answer or keep all blank. If user checks any radio button and finally clicks "Grade Me" button, label text of radio button of any wrong answers checked by the user shall appear as red and at the same time correct answer of that particular question shall appear in green (This will help the user know which question he answered wrong and what is its correct answer). I have tried several steps and searched many forums and failed. I think it will be really simple.
Example:
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
answers[0] = "doesn't like";
answers[1] = "don't come";
answers[2] = "come";
var wrong = new Array(3);
wrong[0] = "don't like";
wrong[1] = "doesn't come";
wrong[2] = "comes";
var wrong1 = new Array(3);
wrong1[0] = "doesn't likes";
wrong1[1] = "doesn't comes";
wrong1[2] = "coming";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < numQues; i++) {
currElt = i * numChoi;
answered = false;
for (j = 0; j < numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
answered = true;
if (currSelection.value == answers[i]) {
score += 3;
break;
}
if (currSelection.value == wrong[i]) {
score -= 1;
break;
}
if (currSelection.value == wrong1[i]) {
score -= 1;
break;
}
}
}
}
var scoreper = Math.round(score * 100 / 9);
form.percentage.value = scoreper + "%";
form.mark.value = score;
}
<title>Quiz Questions And Answers</title>
<center>
<h1>Quiz Questions</h1>
</center>
<p>
<form name="quiz">
<p>
<b><br>1. He -------------------- it.<br></b>
<label><input type="radio" name="q1" value="don't like">don't like</label><br>
<label><input type="radio" name="q1" value="doesn't like">doesn't like</label><br>
<label><input type="radio" name="q1" value="doesn't likes">doesn't likes</label><br>
<p><b>
<hr>
<br>2. They -------------------- here very often.<br></b>
<label><input type="radio" name="q2" value="don't come">don't come</label><br>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label><br>
<p><b>
<hr>
<br>3. John and Mary -------------------- twice a week.<br></b>
<label><input type="radio" name="q3" value="come">come</label><br>
<label><input type="radio" name="q3" value="comes">comes</label><br>
<label><input type="radio" name="q3" value="coming">coming</label>
<br>
<p><b>
<hr>
<p><b>
<input type="button"value="Grade Me"onClick="getScore(this.form);">
<input type="reset" value="Clear"><p>
Number of score out of 15 = <input type= text size 15 name= "mark">
Score in percentage = <input type=text size=15 name="percentage"><br>
</form>
<p>
<form method="post" name="Form" onsubmit="" action="">
</form>
Here is a rewrite of your code.
I fixed the illegal HTML and used best practices with event listeners, querySelectors and CSS
Please study the code and see if you understand. I can add more comments if needed
var answers = ["doesn't like","don't come","come"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
if (checked) score +=3;
}
else if (checked) {
score--;
rad.closest("label").classList.toggle("error")
}
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
.correct {
color: green
}
.error {
color: red
}
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/>
Number of score out of 15 = <input type="text" size="15" id="mark">
Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
In your getScore function, when you find out that a certain element has a correct answer selected (whichever var is the label - unless you are using a custom radio button which I would recommend since changing the background of the label element would simply highlight the words), you can give it a new class using JS.
currSelection.classList.add("correct");
or
currSelection.classList.add("incorrect");
Then in your CSS file you can have rules saying
.correct { background: green !important; }
.incorrect { background: red !important; }
WoW!....Close....Thanks for support. But still all the wrong answers are showing red color. This will let the user know which question he answered wrong. That part is Okay. But once the wrong answers are marked with red(I mean only the wrongly selected radio button choice texts and not the entire question and answer choices
the correct answer of that wrong attempt to be shown in green to enlighten the user. And the sad part is that I again failed with the CSS thing. I wanted to create a quiz in blog and added custom CSS with conditional tag in html of blogger post.....Not Working. However, I will add the modified code here so that you get a clear picture if I am doing rightly as you said.(How and where to add the CSS rules inside this code(if that is what you mean))
var answers = ["doesn't like", "don't come", "come"];
var rads, quiz; // need to be set after load
window.addEventListener("load", function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click", function(e) { // on submit
var score = 0;
var checked = quiz.querySelectorAll("input[type=radio]:checked"); // all checked radios
for (var i = 0; i < checked.length; i++) { // loop over all checked radios in the form
var idx = checked[i].name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var correct = checked[i].value == answers[idx];
checked[i].closest("p").classList.toggle("error", !correct)
checked[i].closest("p").classList.toggle("correct", correct)
score += correct ? 3 : -1; // this is called a ternary
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
<!DOCTYPE HTML>
<html>
<body>
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't https://stackoverflow.com/questions/53818896/change-label-text-of-all-radio-button-in-quiz-as-red-and-green/59801712#like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/> Number of score out of 15 = <input type="text" size="15" id="mark"> Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
</body>
</html>
You can try this:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var coffee = document.forms[0];
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
document.getElementById("score"+i).style.color = "green";
document.getElementById("order").value = "You Clicked Option " + i;
}
} }
</script>
</head>
<body>
<div id="score1" style="font-size: 50px">1</div>
<div id="score2" style="font-size: 50px">2</div>
<div id="score3" style="font-size: 50px">3</div>
<div id="score4" style="font-size: 50px">4</div>
**<form action="/action_page.php">
<input type="text" id="order" size="50">
<br>
<input type="radio" name="coffee" value="1" onclick="myFunction()">Option 1<br>
<input type="radio" name="coffee" value="2" onclick="myFunction()">Option 2<br>
<input type="radio" name="coffee" value="3" onclick="myFunction()">Option 3<br>
<input type="radio" name="coffee" value="4" onclick="myFunction()">Option 4<br>
</form>**
</body>
</html>

Google apps HTML Form - Record and refresh form variable

I struggling with a custom golf stroke HTML form using google's html webapp service. The goal is for the form to dynamically refresh with the new stroke/hole numbers after you click a button. Eventually, it will record each stroke in a google spreadsheet
I can't figure out how to refresh the form and rebuild the html file with the new stroke/hole numbers after clicking either next shot or next hole. My code I have so far is rough as I am just hacking my way through this.
code.gs
function doGet(){
return HtmlService.createHtmlOutputFromFile('Index');
}
function doPost(){
Logger.log("Posted");
}
//hardcoded for testing, will start at 1 for each at beginning of round
var Hole = 11;
var Shot = 22;
var HoleShot = 3;
var DataArr = [Shot, Hole, HoleShot]
function Test() {
Hole++;
Logger.log(DataArr[2]);
Logger.log(HoleShot);
}
function HoleRead() {
return Hole;
}
function ShotRead() {
return Shot;
}
function HoleShotRead() {
return HoleShot;
}
function NextShot() {
//button function to add 1 to total shots and hole shot, but stay on same hole
//then refresh/clear the form and show the new shot number
Shot++;
HoleShot++;
Logger.log(HoleShot);
ShotToSheet();
//refresh or call NEXT html
return HtmlService.createHtmlOutputFromFile('NEXT');
}
function NextHole() {
//add +1 to hole and total shots but reset hole shot back to 1
//then refresh/clear the form and show the new shot/Hole number
}
function Complete() {
}
function ShotToSheet() {
//records teh 3 variables plus date to a row in a google spreadsheet
}
//builds an Input Spreadsheet if one doesnt exist
function SheetExist() {
var my_ss = "HTML To Sheet Test";
var my_sheet = "Input";
var files = DriveApp.getFilesByName(my_ss);
var file = !files.hasNext() ? SpreadsheetApp.create(my_ss) : files.next();
var ss = SpreadsheetApp.openById(file.getId())
try {
ss.setActiveSheet(ss.getSheetByName(my_sheet));
} catch (e) {
ss.insertSheet(my_sheet);
//[TO DO]add headers if first time creating Input Sheet
}
Logger.log(my_ss + " " + my_sheet);
//[TO DO]maybe return IDs or names to be used later
}
html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="ShotForm">
<br>
<span id="TotShot"></span>
<span id="Hole"></span>
<span id="HoleShot"></span>
<fieldset id = "ClubData">Club <br>
<input type="radio" name="Club" id="D" onclick = "ClubClick(this.value);" value="D">
<label for="D">D</label><br>
<input type="radio" name="Club" id="5i" onclick = "ClubClick(this.value);" value="5i">
<label for="5i">5i</label><br>
<input type="radio" name="Club" id="58" onclick = "ClubClick(this.value);" value="58">
<label for="58">58</label><br>
<input type="radio" name="Club" id="P" onclick = "ClubClick(this.value);" value="P">
<label for="P">P</label><br>
<br>
Type <br>
<input type="radio" name="Type" id="Tee Shot" onclick = "TypeClick(this.value);" value="Tee Shot">
<label for="Tee Shot">Tee Shot</label><br>
<input type="radio" name="Type" id="Fairway" onclick = "TypeClick(this.value);" value="Fairway">
<label for="Fairway">Fairway</label><br>
<input type="radio" name="Type" id="Rough" onclick = "TypeClick(this.value);" value="Rough">
<label for="Rough">Rough</label><br>
<input type="radio" name="Type" id="Green" onclick = "TypeClick(this.value);" value="Green">
<label for="Green">Green</label><br>
<br>
Distance <br>
<input type="number" name="Distance" onchange = "DistanceEdit(this.value);" min="1" max="1000">
</fieldset>
<span id="TotShot2"></span>
<span id="Hole2"></span>
<span id="HoleShot2"></span>
will be recorded as:<br>
<span id="Choice1">Club</span> -
<span id="Choice2">Type</span> -
<span id="Choice3">Distance</span>
<br> <br>
<input type="submit" name="NextShotButt" onclick = "NextShot();"value="Next Shot"><br> <br>
<input type="button" name="NextHoleButt" onclick = "NextHole();" value="Next Hole"><br> <br>
<input type="button" name="Complete" onclick = "Complete();" value="Complete">
</form>
</body>

Making javascript check what radio form has been selected

I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...

what's wrong with start1()?

Does anyone know what's wrong with start1()? I know that something is not right but I just can't figure what is it.
I have got this school project where i need to do a quiz and record the time that people need to answer all the questions. I've tried everything i know but nothing works. please help
<body>
<div id="classic">
<input type="button" onclick="start1= setInterval(contador, 1000)" value="yes">
<input type="button" onclick="back1()" value="Menu">
</div>
<div id="quizr" hidden>
<h1> who sings the song </h1>
<div id="P1">
<p>1.'Thinking Out Loud'</p>
A)<input type="radio" name="q1" id="q1r1" > Hozier<br>
B)<input type="radio" name="q1" id="q1r2" > Jason Derulo<br>
C)<input type="radio" name="q1" id="q1r3" > Ed Sheeran<br>
D)<input type="radio" name="q1" id="q1r4" > Mr. Probz<br>
<br>
<input type="button" onclick='go1()' value="next »" >
</div>
<div id="P2" hidden>
<p>2.'GANGNAM STYLE'</p>
A)<input type="radio" name="q15" id="q15r1" > Tori Kelly<br>
B)<input type="radio" name="q15" id="q15r2" > Jessie J<br>
C)<input type="radio" name="q15" id="q15r3" > Beyoncé<br>
D)<input type="radio" name="q15" id="q15r4" > Psy<br>
<br>
<input type="button" onclick='verify1= clearInterval(start1)'value="submit">
</div>
</div>
<div id="result" hidden></div>
function start1()
{
document.getElementById("classic").hidden=true;
document.getElementById("quizr").hidden=false;
}
var t= 0;
function contador()
{
document.getElementById("resultado").innerHTML = ++t;
}
function go1()
{
document.getElementById("P1").hidden= true;
document.getElementById("P2").hidden = false;
}
function verify1()
{
document.getElementById("P2").hidden = true;
document.getElementById("result").hidden = false;
var correctAnswers= 0;
var question1 = document.getElementById("q1r3").checked;
if (question1 === true)
{
correctAnswers = correctAnswers + 1;
}
var question2 = document.getElementById("q2r4").checked;
if (question2 === true)
{
correctAnswers = correctAnswers + 1;
}
document.getElementById("resultado").innerHTML = correctAnswers + "/15" + " " + " correct" + " "+ "answers";
}
This is just a readonly. See the docs:
hidden
Is a Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.
What you must really do is:
document.getElementById("classic").style.display = 'none';
document.getElementById("quizr").style.display = 'block';

Categories

Resources