Trying to convert my JavaScript into JQuery - javascript

I'm trying to convert my Javascript code into JQuery but I know I did something wrong when calling the function. I'm having a tough time knowing exactly what to put when trying to call the radio elements by name.
Original Javascript works, but I'm not sure how to get the JQuery version to work.
Index HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created?</p>
<input type="radio" name="question0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="question0" value="B">Donald Duck<br>
<input type="radio" name="question0" value="C">Mickey Mouse<br>
<input type="radio" name="question0" value="D">Goofy<br>
<p id="flag0"><p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully.</p>
<input type="radio" name="question1" value="A">Movie<br>
<input type="radio" name="question1" value="B">Live-Action<br>
<input type="radio" name="question1" value="C">Cel-animated Film<br>
<input type="radio" name="question1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<section id="radio3">
<p> Question 3) Walt left a big impression when he had created ____ films for the U.S. government</p>
<input type="radio" name="question2" value="A">Peacemaker<br>
<input type="radio" name="question2" value="B">Political<br>
<input type="radio" name="question2" value="C">World War II<br>
<input type="radio" name="question2" value="D">Religious<br>
<p id="flag2"><p>
</section>
<section id="radio4">
<p> Question 4) Which of the following is true?</p>
<input type="radio" name="question3" value="A">Disney at first wanted to become a filmmaker<br>
<input type="radio" name="question3" value="B">Disney has made multiple controversial cartoons.<br>
<input type="radio" name="question3" value="C">Disney holds the record for most individual Oscar wins.<br>
<input type="radio" name="question3" value="D">Heart failure was the cause of Disney's death.<br>
<p id="flag3"><p>
</section>
<section id="radio5">
<p> Question 5) Which of the following has been rumored to happen to Walt Disney after his death?</p>
<input type="radio" name="question4" value="A">Faked his death<br>
<input type="radio" name="question4" value="B">Cremated<br>
<input type="radio" name="question4" value="C">Buried<br>
<input type="radio" name="question4" value="D">Cryogenically frozen<br>
<p id="flag4"><p>
</section>
<br>
<button type="button">Show Results</button>
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
Original JavaScript
var answers = ["A","C","B","C","D"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
JQuery
var answers = ["A","C","B","C","D"],
total = answers.length;
$(function getCheckedValue()
{
var radios = $('[name="question"]');
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
});
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
$("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
});
$(function returnScore()
{
var x = $("myText").value;
$("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
});

You don't need to put function definitions inside $(...), just put it at top-level just like in your plain JS version. $(...) is for code that needs to run after the DOM is loaded, but you don't need to wait to define functions. It will also call the functions you define there, not just define them.
The jQuery version of getCheckValue() isn't using the parameter, you need to add that.
And selectors for IDs need to begin with #.
function getCheckedValue(radioname)
{
return $(`[name="${radioname}"]:checked:first`).val();
}
In getScore your else if condition is the opposite of the if condition. So you should just use else. And jQuery uses the .html() and .text() functions to fill in an element, you don't assign to .innerHTML.
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else
{
$("#flag"+i).text("Your answer is incorrect.");
}
}
return score;
});
function returnScore()
{
var x = $("#myText").value;
$("#results").html(x + ", your score is " + getScore() + "/" + total);
}
In the HTML, you need to change the order that you load the scripts:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="scripts/quiz.js"></script>
Since quiz.js uses jQuery, jQuery has to be loaded first.

Related

Javascript quiz with multiple radio and text input types

I've made a small test/quiz with radio and checkbox types. Radio button in my code is mandatory to be checked and when it is, I get the total score for all correct answers, when it's not I get alert message that i need to check all questions.
Now I want to expand this quiz.
1st problem: I've made multiple radio type questions, I don't know how to check if all radio type questions are checked.
2nd problem: I've made test type questions and I want them to be seen after I push "Finish" (alongside total score from test questions), but when I push "Finish" I do not see the text type answers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./CSS/reset.css">
<link rel="stylesheet" href="./CSS/main.css">
<title>Exam</title>
<script src="./JS/assessor.js"></script>
</head>
<body>
<section>
<main>
<h2>This is the exam</h2>
<form name="exam" id="exam">
<div class="question">
<div class="questionTitle">Question 1</div>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="right">right</p>
</div>
<div class="question">
<div class="questionTitle1">Question 1</div>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="right">right</p>
</div>
<div class="question">
<div class="questionTitle">Question 2</div>
<p><input type="checkbox" id="answer2wrong1" name="answer2_1" value="wrong">wrong</p>
<p><input type="checkbox" id="answer2right1" name="answer2_2" value="right">right</p>
<p><input type="checkbox" id="answer2right2" name="answer2_2" value="right">right</p>
<p><input type="checkbox" id="answer2wrong2" name="answer2_4" value="wrong">wrong</p>
</div>
<div>
<label for="fname">First field</label><br>
<input type="text" id="fname" name="fname" value="button1"><br>
<label for="fname">Second field</label><br>
<input type="text" id="fname" name="fname" value="button2"><br>
<label for="fname">Third field</label><br>
<input type="text" id="fname" name="fname" value="button3"><br>
</div>
<input type="button" id="button" name="" value="Finish" onclick="validate();assess()">
</form>
<p id="result"></p>
</main>
</section>
</body>
</html>
function validate() {
var valid = false;
var x = document.exam.answer1;
for(var i=0; i<x.length; i++) {
if (x[i].checked) {
valid= true;
break;
}
}
if(valid) {
assess();
}
else {
alert("All questions must be checked");
return false
}
function assess() {
var score=0;
var q1=document.exam.answer1.value;
var result=document.getElementById('result');
var exam=document.getElementById('exam');
if (q1=="right") {score++}
if (answer2right1.checked===true) {score += 0.5}
if (answer2right2.checked===true) {score += 0.5}
if (answer2wrong1.checked===true) {score -= 0.5}
if (answer2wrong2.checked===true) {score -= 0.5}
exam.style.display="none";
result.textContent=`${score}`;
}
}
Nobody replies to me so I try to figure it out myself. Yet I face problems.
1st example:
I get Success when i check 1st questions answer, but i need to check if all questions are checked, and I need to do it at once. In this code i can only check 1 question's status wether checked or not.
var mark = document.getElementsByTagName('input');
for (var i=0; i<mark.length; i++) {
if (mark[i].type == 'radio' && mark[i].name=="answer1" && mark[i].checked==true) {
alert("YES")
break;
}
}
2nd example:
In this code it doesnt recognize my ID at all and neither true or false work.
if(document.getElementById("answer1").checked==true) {
alert("Success");
}
else {
alert("All questions must be checked");
}
I figured it out myself. I added few lines where for checked answer in every question the "filledQuestion" score increases by 1. Then if "filledQuestion" score is equal to the number of questions, it passes, if not, it shows error message.
function validate() {
var mark = document.getElementsByTagName('input');
var filledQuestion = 0;
for (var i=0; i<mark.length; i++) {
if (mark[i].type == 'radio' && mark[i].name=="answerR1" && mark[i].checked==true) {
filledQuestion = filledQuestion + 1
}
else if (mark[i].type == 'radio' && mark[i].name=="answerR2" && mark[i].checked==true) {
filledQuestion = filledQuestion + 1
break;
}
}
if (filledQuestion == 2) {
assess();
showDiv();
}
else (alert("All questions must be checked"))
My second issue was due to my choice to use ( exam.style.display="none"; ) line. When i do not use it, the score is visible in the same page and therefore i can see all the changes after i submit the form.

Radio button selection when building HTML form

I have a simple HTML form that is used for bookings. Once completed it submits the fields via e-mail which can then be automatically uploaded into my Access database with VBA.
The process works fine if there is just text in the form but I want to include radio button choices as well. The problem is that it doesn't include an indication as to which button has been chosen.
The body of the e-mail, if "text" was entered into the text box and choice2 was selected would be:
text
Choice1
Choice2
Choice3
What I would like it to be is:
text
Choice2.
Can this be done?
A simplified version of my code so far is:
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
str += elem[i].value + "\r\n";
}
}
return str;
}
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
You need to check if the element is checked.
And since you're adding it in the same loop as the text field you also need to make sure the element that has to be checked is actually a radio button:
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
But: In your snippet everything is added to the TO field of the mail, is that intended?
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
}
}
return str;
}
<html>
<head>
<title>Radio button trial</title>
</head>
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
</body>
</html>

Want to make it so prices actually reflect the choices

Hope everyone is having a good weekend!
If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings === "Cheese") {
this.pizzaPrice += 3;
}
else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
this.pizzaPrice += 10;
console.log("hey");
}
else if (this.toppings === "Vegetarian") {
this.pizzaPrice += 2;
}
else if (this.toppings === "Supreme") {
this.pizzaPrice += 4;
}
else if (this.toppings === "Pepperoni") {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>
Firstly, you need to get values of all checked toppings in an array, currently you are getting only the first one. Then you need to add prices for each topping selected while calculating the price. you can use indexOf for this:
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Cheese") >= 0) {
this.pizzaPrice += 3;
}
if (this.toppings.indexOf("Peanut Butter") >= 0) {
this.pizzaPrice += 10;
}
if (this.toppings.indexOf("Vegetarian") >= 0) {
this.pizzaPrice += 2;
}
if (this.toppings.indexOf("Supreme") >= 0) {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Pepperoni") >= 0) {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = [];
$("input[type=checkbox][name=toppings]:checked").each(function(){
toppings.push($(this).val());
});
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>
The statement here
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
is incorrect. As it is returning you the value of first checked checkbox.
Instead use following statement to get an array of checked values.
var toppings = $("input[type=checkbox][name=toppings]:checked").get();
Now while retrieving the values you can use the following:
(this.toppings.indexOf("Cheese") >= 0)
The indexOf() returns -1 if no matching results is found.
Hope this solves your problem.
There are a number of issues -
1.) When you do
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
you already lost all the toppings except the first one. Instead you could use
var toppings = $("input[type=checkbox][name=toppings]:checked");
var i = 0;
var toppingVal;
while(i < toppings.length){
toppingVal += " "+(toppings[i]).value;
i++;
}
2.) When you are calculating the price, you make use of if..else..if blocks. How can you add up multiple toppings, only one block would execute. use only if
3.) As per my suggestion you would get a string of toppings seperated by a space(' '). So you cannot be using === for comparison. Use indexOf to find if the toppings string contains a specific topping.
Take a look at this fiddle
https://jsfiddle.net/8u67x4nm/1/ . Works fine.

Grading a test - Loop checking radio input values (JS)

I am working on an online test where you get your output directly. I get stuck at checking the values of the radio input with a loop. Why gives the checkFields function output undefined?
Javascript Code:
<script type="text/javascript">
$(document).ready(function(){
//click button
$("#submitTest").click(function(){
//check if all answers are given
for (i = 1; i <= 10; i++) {
if (checkFields([i].toString())) {
//calculate total score
if ($("input[name=[i]]").val() == aq[i]) {score = score + 1};
}
else{alert("Please answer all questions");
break}};
console.log(score);
//return level of English
}
)
//setFunction
function checkFields(Q){
console.log(
$("[name='[Q]']:checked").val())
}
//Set score 0
var score = 0;
//Answers
var aq1 = "a1";
var aq2 = "a1";
var aq3 = "a3";
var aq4 = "a2";
var aq5 = "a1";
var aq6 = "a2";
var aq7 = "a3";
var aq8 = "a3";
var aq9 = "a1";
var aq10 = "a1";
}
)
</script>
HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- liberaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<!-- Q1 -->
<p class="question">1. Can I park here?</p>
<input type="radio" id="1" name="1" value="a1">a1<br>
<input type="radio" id="1" name="1" value="a2">a2<br>
<input type="radio" id="1" name="1" value="a3">a3
<!-- Q2 -->
<p class="question">2. Can I park here?</p>
<input type="radio" name="2" value="a1">a1<br>
<input type="radio" name="2" value="a2">a2<br>
<input type="radio" name="2" value="a3">a3
<!-- Q3 -->
<p class="question">3. Can I park here?</p>
<input type="radio" name="3" value="a1">a1<br>
<input type="radio" name="3" value="a2">a2<br>
<input type="radio" name="3" value="a3">a3
<!-- Q4 -->
<p class="question">4. Can I park here?</p>
<input type="radio" name="4" value="a1">a1<br>
<input type="radio" name="4" value="a2">a2<br>
<input type="radio" name="4" value="a3">a3
<!-- Q5 -->
<p class="question">5. Can I park here?</p>
<input type="radio" name="5" value="a1">a1<br>
<input type="radio" name="5" value="a2">a2<br>
<input type="radio" name="5" value="a3">a3
<!-- Q6 -->
<p class="question">6. Can I park here?</p>
<input type="radio" name="6" value="a1">a1<br>
<input type="radio" name="6" value="a2">a2<br>
<input type="radio" name="6" value="a3">a3
<!-- Q7 -->
<p class="question">7. Can I park here?</p>
<input type="radio" name="7" value="a1">a1<br>
<input type="radio" name="7" value="a2">a2<br>
<input type="radio" name="7" value="a3">a3
<!-- Q8 -->
<p class="question">8. Can I park here?</p>
<input type="radio" name="8" value="a1">a1<br>
<input type="radio" name="8" value="a2">a2<br>
<input type="radio" name="8" value="a3">a3
<!-- Q9 -->
<p class="question">9. Can I park here?</p>
<input type="radio" name="9" value="a1">a1<br>
<input type="radio" name="9" value="a2">a2<br>
<input type="radio" name="9" value="a3">a3
<!-- Q10 -->
<p class="question">10. Can I park here?</p>
<input type="radio" name="10" value="a1">a1<br>
<input type="radio" name="10" value="a2">a2<br>
<input type="radio" name="10" value="a3">a3
</form>
<!-- Submit -->
<button id="submitTest">Submit Test!</button>
</body>
</html>
This code might not be the way to do it. I tried various ways but did not manage.
edited below
New code
https://jsfiddle.net/5fnugrts/#&togetherjs=AOK0k8r4i2
HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Libaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<div id="myForm"></div>
</form>
<!-- Submit button -->
<button id="submitTest">Submit Test!</button>
Javascript Code
<!-- JS -->
<script type="text/javascript">
$(document).ready(function() {
//Answers and Questions constructor ("question","answer1","answer2","answer3","a"+number of correct answer)
function Question(question, answer1, answer2, answer3, correctAnswer) {
this.q = question;
this.a1 = answer1;
this.a2 = answer2;
this.a3 = answer3;
this.ca = correctAnswer;
};
//Answers and Questions ("question","answer1","answer2","answer3","a"+number of correct answer)
var aQ = {
Q1: new Question("What is the correct answer 1?", "Cheese", "Ham", "Turkey", "a1"),
Q2: new Question("What is the correct answer 2?", "Cheese", "Ham", "Turkey", "a1"),
Q3: new Question("What is the correct answer 3?", "Cheese", "Ham", "Turkey", "a2"),
Q4: new Question("What is the correct answer 4?", "Cheese", "Ham", "Turkey", "a2"),
Q5: new Question("What is the correct answer 5?", "Cheese", "Ham", "Turkey", "a3"),
};
//Set Setinhtml function ("name of radio group" "question","answer1","answer2","answer3","a"+number of correct answer)
function appendQuestion(groupName, question, answer1, answer2, answer3) {
$("div#myForm").append("<p class=\"question\">" + question + "</p>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a1\">" + answer1 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a2\">" + answer2 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a3\">" + answer3 + "<br>")
};
//Set in HTML loop
for (i = 1; i <= Object.keys(aQ).length; i++) {
appendQuestion([i],
eval("aQ.Q" + [i] + ".q"),
eval("aQ.Q" + [i] + ".a1"),
eval("aQ.Q" + [i] + ".a2"),
eval("aQ.Q" + [i] + ".a3"),
eval("aQ.Q" + [i] + ".ca"))
};
//Sumbit answers
$("#submitTest").click(function() {
score = 0
//Loop and give values
for (i = 1; i <= Object.keys(aQ).length; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = eval("aQ.Q" + i + ".ca")
//Check if answers are filled in
if (!tAnswer) {
alert("Please answer all questions");
return;
}
//Check correct answers
else if (tAnswer == cAnswer) {
score++
}
}
//Report score
alert("Your score is " + score + "/" + Object.keys(aQ).length);
});
});
</script>
I tweaked your code to make it more compact and effecient
Here's a codepen
$(document).ready(function() {
//Set score 0
var score = 0;
//Answers
aq1 = "a1";
aq2 = "a1";
aq3 = "a3";
aq4 = "a2";
aq5 = "a1";
aq6 = "a2";
aq7 = "a3";
aq8 = "a3";
aq9 = "a1";
aq10 = "a1";
$("#submitTest").click(function() {
score = 0
for (i = 1; i <= 10; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = window["aq"+i]
if (!tAnswer) {
alert("Please answer all questions");
return;
} else if (tAnswer == cAnswer) {
console.log("#"+i+": correct")
score++
} else if (tAnswer != cAnswer) {
console.log("#"+i+" incorrect")
}
}
alert("Your score is "+ score +"/10");
});
});
tAnswer is the answer and cAnswer is the correct answer, you can also check if(!cAnswer) then you didn't define the correct answer.

How can I display a text value for radio buttons using javascript

I am building an online store where the customer can select custom parts.
I'm quite new to javascript, but I've managed to create a radio button list, where the price is added from each section.
I would like a box to show all of the options selected, not just the sum total.
I've included the text with value and used parseInt. Is there an equivalent I can use to pull the text, not the number, from the value?
My code so far:
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.part.length; i++ ){
if( document.form1.part[i].checked == true ){
val1 = document.form1.part[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.part2.length; i++ ){
if( document.form2.part2[i].checked == true ){
val2 = document.form2.part2[i].value;
}
}
var val3 = 0;
for( i = 0; i < document.form3.part3.length; i++ ){
if( document.form3.part3[i].checked == true ){
val3 = document.form3.part3[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2) + parseInt(val3);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="0 1.8ghz2xAMD" name="part" checked="checked" onclick="DisplayPrice(this.value);">1.8Ghz Dual Core AMD
<br>
<input id="rdo_2" type="radio" value="50 2ghz2xAMD" name="part" onclick="DisplayPrice(this.value);">2Ghz Dual Core AMD
<br>
</form>Choose your memory:<br />
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="0 1333corsair1gb" name="part2" checked="checked" onclick="DisplayPrice(this.value);">1333 Corsair 1GB
<br>
<input id="rdo_2" type="radio" value="50 1333corsair2x1gb" name="part2" onclick="DisplayPrice(this.value);">1333 Corsair 2x1GB
<br>
</form>Choose your graphics card:<br />
<form name="form3" id="form3" runat="server">
<br />
<input id="rdo_1" type="radio" value="0 5830ATI1gb" name="part3" checked="checked" onclick="DisplayPrice(this.value);">1GB ATI 5830
<br />
<input id="rdo_2" type="radio" value="50 5850ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5850
<br />
<input id="rdo_3" type="radio" value="75 5870ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5870
<br />
</form>
</body>
Thanks in advance for any advice you can give.
The values seem to be consistently separated by a space. So you could use split() function to split the value in two parts, the first part containing the price and the second part containing the text.
var parts = value.split(" ");
var price = parseInt(parts[0]);
var text = parts[1];
That said, there are better/nicer ways to achieve the functional requirement, but that's up to you to as an learning exercise.

Categories