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>
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.
i made some code recently but im wondering how to make the quiz choose 3 questions out of 6 instead of displaying 6 straight away. Help would be appreciated. I want the quiz to choose 3 questions at random, then if its reloaded have a chance to choose another 3 questions, out of a total pool of 6.
<script language="JavaScript">
var numQues = 6;
var numChoi = 3;
var answers = new Array(6);
answers[0] = "16";
answers[1] = "8";
answers[2] = "The Walking Dead";
answers[3] = "Batman v Superman";
answers[4] = "Tupac";
answers[5] = "#ATAME2016";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
</script>
</head>
<body>
<form name="quiz">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
<p>
2. How many pages are on this website?<br>
<input type="checkbox" name="q2" value="8">8<br>
<input type="checkbox" name="q2" value="6">6<br>
<input type="checkbox" name="q2" value="7">7<br>
<p>
3. What's the most popular show this week?<br>
<input type="checkbox" name="q3" value="The Walking Dead">The Walking Dead<br>
<input type="checkbox" name="q3" value="Mandem on the wall">Mandem on the wall<br>
<input type="checkbox" name="q3" value="Cotchin with Ksara">Cotchin with Ksara<br>
<p>
4. What movie has made the most money this week in the box office?<br>
<input type="checkbox" name="q4" value="Ride along 2">Ride along 2<br>
<input type="checkbox" name="q4" value="Batman v Superman">Batman v Superman<br>
<input type="checkbox" name="q4" value="GasMan">GasMan<br>
<p>
5. Which star in the celebrity page is no longer alive?<br>
<input type="checkbox" name="q5" value="Tupac">Tupac<br>
<input type="checkbox" name="q5" value="50 Cent">50 Cent<br>
<input type="checkbox" name="q5" value="Bradley cooper">Bradley cooper<br>
<p>
6. What is our twitter account name (#)?<br>
<input type="checkbox" name="q6" value="#ATAME">#ATAME<br>
<input type="checkbox" name="q6" value="#ATAME2016">#ATAME2016<br>
<input type="checkbox" name="q6" value="#A2THETAME">#A2THETAME<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>
</div>
You'll want to use a Math.random() function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
A common example is found at: http://www.w3schools.com/jsref/jsref_random.asp
I'd try something like this, using jQuery:
// Hides all questions on page load.
$('.questions').hide();
// Randomly shows 3 questions.
for (var i=0; i<3; i++) {
var questionId = Math.floor((Math.random() * 6) + 1);
$('#question-' + questionId).show();
}
Then wrap your questions in wrapping <div> or <p> tags like this:
<div id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</div>
Or this:
<p id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</p>
I'm trying to create a 5 star radio picker.
This is the 1 of the radio buttons:
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
After the method gets called and "3" is passed on this is my javascript function:
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
When I run the code, it does not perform the checked to = true, though if remove the for loop, it works just fine.
Any ideas why the for loop is preventing from checking the radio boxes?
This is my entire code:
<script>
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
</script>
<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>
Thanks!
i had to be 1 initially as ids are starting from 1
Also reset all the checked status when click is initiated! Use i instead of stars in getElementById
Try this:
function check(stars) {
for (var j = 1; j <= 5; j++) {
document.getElementById("num_" + j + "_star").checked = false;
}
for (var i = 1; i <= stars; i++) {
document.getElementById("num_" + i + "_star").checked = true;
}
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
Put var before the iteration variable i. You are creating a global variable.
I'm trying to create a Quiz for a Spanish class. I have little experience with JavaScript, but am fairly proficient with html and CSS. I have a question and followed by three radio buttons with answers. There are two incorrect answers and a correct answer. I have 45 questions total.
<form name="quiz" method="post" name="buttons" id="form" onsubmit="return totalVal()">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="showTotalvalue();" type="submit">Submit</button></div>
I want to use some basic Javascript to count all the "correct" radio button values and output to a new page or alert box that displays after the user clicks submit.
I found this in my research. In my googling, I haven't been able to find a snippet of code that counts the "correct" values. The link above is the closest I've gotten. I attached the JavaScript that I changed to fit my situation from the suggestion on the other post.
totalVal = 0;
// calculate the total number of corrects clicked
for (y = 0; y = incorrectOfQuestion; y++) {
var questionNo = document.getElementsByName("questions" + y);
for (i = 0; i < questionNo.length; i++) {
if (document.myform.questions[i].checked == true) {
totalVal = totalVal + parseInt(document.myform.questions[i].value, 45);
}
}
}
Any assistance is greatly appreciated as I am in a time crunch! Thank you!
This should be the code you require to get it working with an alert box:
function handleClick()
{
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName('group'+i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value == "correct" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct Responses: " + amountCorrect);
}
<form name="quiz" method="post" name="buttons" id="quiz" onsubmit="return false">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="return handleClick();" type="submit">Submit</button>
</form>
#pimvdb had used the === operator when checking for the "correct" string which does not allow type conversion and was therefore failing. He also used getElementsByClassName but the elements do not have a class applied to them so this was incorrect.
The working version can be found in the fiddle below. As you can see the onsubmit of the form has been set to "return false" to stop the form from posting.
http://jsfiddle.net/g45nG/1/
You can loop over each radio group, then loop over each radio button to check whether the correct one is checked.
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName("group" + i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value === "correct" && radio.checked) {
amountCorrect++;
}
}
}