fill in the blank and multiple choice quiz - javascript

I was wondering if someone could help me? In my code below what if answers in question 2 were allowed to be in any order? Like: hips,body,knees or knees,hips,body and so on. How should I modify my code? Anyone please????
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Quiz</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
var answer_list = [
['False'],
['body,hips,knees']
// Note: No comma after final entry
];
var response = [];
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
function setAnswer(question, answer) {
response[question] = answer;
}
function CheckAnswers() {
var correct = 0;
var resp, answ;
for (var i = 0; i < answer_list.length; i++) {
resp = response[i].toString();
resp = resp.toLowerCase();
answ = answer_list[i].toString();
answ = answ.toLowerCase();
//#################################################################################################
if (resp == answ) {
correct++;
if(i==0){
document.forms[0].a1c.style.backgroundImage="url('correct.gif')";
document.forms[0].a1c.value = "";
}
else{
document.forms[0].a1d.style.backgroundImage="url('correct.gif')";
document.forms[0].a1d.value = "";
}
}
else{
if(i==0){
document.forms[0].a1c.style.backgroundImage = "url('incorrect.gif')";
document.forms[0].a1c.value = " ANS: False. Position the head snugly against the top bar of the frame and then bring the foot board to the infant's feet.";
}
else{
document.forms[0].a1d.style.backgroundImage = "url('incorrect.gif')";
document.forms[0].a1d.value = " ANS: " + answ;
}
//###################################################################################################
}
}
document.writeln("You got " + correct + " of " + answer_list.length + " questions correct!");
}
</script>
</head>
<body>
<form action="" method="post">
<div>
<b>1. When measuring height/length of a child who cannot securely stand, place the infant such that his or her feet are flat against the foot board.</b><br />
<label><input type="radio" name="question0" value="True" />True</label>
<label><input type="radio" name="question0" value="False" />False</label>
<br />
<textarea rows="2" cols="85" name="a1c" style="background-repeat:no-repeat"></textarea>
<br />
<b>2. When taking a supine length measurement, straighten the infant's
<input type="text" name="question1_a" size="10" />,
<input type="text" name="question1_b" size="10" />, and
<input type="text" name="question1_c" size="10" />.</b>
<br />
<textarea rows="2" cols="85" name="a1d" style="background-repeat:no-repeat"></textarea>
<br />
<input type="button" name="check" value="Check Answers" onclick="setAnswer(0,getCheckedValue(document.forms[0].question0));setAnswer(1,[document.forms[0].question1_a.value,document.forms[0].question1_b.value,document.forms[0].question1_c.value]);CheckAnswers();" />
</div>
</form>
</body>
</html>

The easiest way IMO is to sort the user's answers and sort the correct answers in CheckAnswers().

Related

HTML/Javascript Radio Button Quiz

I'm trying to validate the radio buttons so that an error pops up when it's not checked.
However the error won't disappear unless I select an option from the Question 2 set and nothing from Question 1.
I'm trying to have both messages pop up for both questions if unchecked and and individually disappear when something is selected for that question
//Javascript
var answers = ["A","C"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpan = document.getElementById("choice_error");
var isChecked = false;
errorSpan.innerHTML = "";
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpan.innerHTML = "Please select a choice.";
}
}
return isChecked;
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("choice"+i) == answers[i])
{
score += 1;
document.getElementById("flag"+i).innerHTML = "Your answer is correct.";
}
else if(getCheckedValue("choice"+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;
}
<!--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>
</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" placeholder="First Last"value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created? <span id="choice_error"></span></p>
<input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="choice0" value="B">Donald Duck<br>
<input type="radio" name="choice0" value="C">Mickey Mouse<br>
<input type="radio" name="choice0" 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. <span id="choice_error"></span></p></p>
<input type="radio" name="choice1" value="A">Movie<br>
<input type="radio" name="choice1" value="B">Live-Action<br>
<input type="radio" name="choice1" value="C">Cel-animated Film<br>
<input type="radio" name="choice1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
fastest method:
HTML:
<span id="choice_error_choice0"></span>
<!-- ... -->
<span id="choice_error_choice1"></span>
JS:
function getCheckedValue(radioName)
{
let isChecked = true;
let exist = document.querySelector(`input[name='${radioName}']:checked`);
let choice_error = document.getElementById('choice_error_'+radioName);
choice_error.innerHTML = "";
if (exist == null)
{
isChecked = false;
choice_error.innerHTML = "Please select a choice.";
}
return isChecked;
}
In your code both error spans have the same ID "choice_error". No two html elements should have the same id, as then the browser won't be able to differentiate them.
If you want to access both error span elements, you can give each of them a ccs class "choice_error" and call the method document.getElementsByClassName().
Also you need to clear the error span inside the loop
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpans = document.getElementsByClassName("choise_error");
var isChecked = false;
for (var y = 0; y < radios.length; y++)
{
errorSpans[y].innerHTML= ""; // clear the span
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpans[y].innerHTML = "Please select a choice."; // error message
}
}
return isChecked;
}
I've tidied a couple of things up. Using label for a start.
The main difference is I now use a parent question id to group our answers and change to class for choice_error.
Then I've use document.querySelector to find the checked answer and set the child error messages display style.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function getAnswer(QuestionId) {
//Get the selected answer radio button
var answer = document.querySelector("#" + QuestionId + " input[type=radio]:checked");
//It there isn't one
if (answer === null) {
//show the error mesage
document.querySelector("#" + QuestionId + " .choice_error").style.display = "inline";
} else {
//Otherwise hide the message
document.querySelector("#" + QuestionId + " .choice_error").style.display = "";
//And set the answer value
answer = answer.value;
}
return answer;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
document.getElementById("flag" + i).innerHTML = "";
if (getAnswer("radio" + (i + 1)) == answers[i]) {
score += 1;
document.getElementById("flag" + i).innerHTML = "Your answer is correct.";
}
/*No need to check again, it either matches or doesn't*/
else {
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;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--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>
</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" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
We could refactor this some more, let one method handle manipulating the question related actions.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function checkAnswer(QuestionId, Answer) {
var isCorrect = false;
var questionElement = document.getElementById(QuestionId);
//Get the selected answer radio button
var answerElement = questionElement.querySelector("input[type=radio]:checked");
//It there isn't one
if (answerElement === null) {
//show the error mesage
questionElement.querySelector(".choice_error").style.display = "inline";
questionElement.querySelector("[id^=flag]").innerHTML = "";
} else {
//Otherwise hide the message
questionElement.querySelector(".choice_error").style.display = "";
//And chcek answer
isCorrect = Answer == answerElement.value;
questionElement.querySelector("[id^=flag]").innerHTML = "Your answer is " + (isCorrect ? "correct" : "incorrect");
}
return isCorrect;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
if(checkAnswer("radio" + (i + 1), answers[i])) {
score++;}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--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>
</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" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>

Why do I get Uncaught TypeError while I've defined it?

I'm trying to make a quiz, here is the html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>English Test</title>
<link rel="stylesheet" href="testCss.css">
</head>
<body>
<br>
<div style="font-size:20px">
<p>Please choose the correct answer and at the end tap the score button. </p>
<br>
<div>
2. I
<select id="question2">
<option value="_">_</option>
<option value="Am">am</option>
<option value="Is">is</option>
<option value="Are">are</option>
</select>
22 years old.
<span id="question2_answer"></span>
</div>
<br>
<br>
<div>
101. When can we meet again?
<span id="question101_answer"></span>
<div>
<input type="radio" name="question101" > When are you free?<br>
<input type="radio" name="question101" > It was two days ago. <br>
<input type="radio" name="question101" > Can you help me?
</div>
</div>
<br>
<br>
<div>
8. What is your father like?
<span id="question8_answer"></span>
<div>
<input type="radio" name="question8" > He likes listenning to music.<br>
<input type="radio" name="question8" > He likes to play football. <br>
<input type="radio" name="question8" > He is friendly.<br>
<input type="radio" name="question8" > He has a car.
</div>
</div>
<br>
<br>
<button id="button1" class="button" onclick="viewScore()">Score Result</button>
<br>
<input type="text" id="grade1" value="" readonly>
<br>
<script src="testJs.js"></script>
and here is the testJs.js that i used:
var score = 0;
function viewScore() {
var answer2 = document.getElementById("question2").value;
var answer8 = document.getElementsByName("question8");
var answer101 = document.getElementsByName("question101").value;
if (answer2 == "Am") {
document.getElementById("question2_answer").style.color = "green";
document.getElementById("question2_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question2_answer").style.color = "red";
document.getElementById("question2_answer").innerHTML = "&#10006 Wrong!";
}
if (answer8[2].checked) {
document.getElementById("question8_answer").style.color = "green";
document.getElementById("question8_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question8_answer").style.color = "red";
document.getElementById("question8_answer").innerHTML = "&#10006 Wrong!";
}
if (answer101[0].checked) {
document.
getElementsById("question101_answer").style.color = "green";
document.getElementsById("question101_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementsByID("question101_answer").style.color = "red";
document.getElementsByID("question101_answer").innerHTML = "&#10006 Wrong!";
}
if (score<=5) {
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Elementary.";
} else if(score<=8){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Pre Intermediate.";
}else if(score<=15){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Intermediate.";
}else{
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Upper Intermediate.";
}
console.log(score);
score = 0;
}
However, I'm getting following error on question 101. I check it several times and I have no idea where does this error coming from ! It refers to question 101 and mentions cannot read property '0' of undefined.
Thanks for any help in advance.
testJs.js:26 Uncaught TypeError: Cannot read property '0' of undefined
at viewScore (testJs.js:26)
at HTMLButtonElement.onclick (testHTML.html:57)
This is happening because in this line:
var answer101 = document.getElementsByName("question101").value;
you are putting the value of the input (which is NULL or UNDEFINED because the HTMLCollection returned by getElementsByName (note the plural) doesn't have a value property) into the var answer101 and NOT the input itself.
To fix this, change the above line to:
var answer101 = document.getElementsByName("question101");
You have to select array (not value) for var answer101
var answer101 = document.getElementsByName("question101");
And correct if content for answer101
if (answer101[0].checked) {
document.getElementById("question101_answer").style.color = "green";
document.getElementById("question101_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question101_answer").style.color = "red";
document.getElementById("question101_answer").innerHTML = "&#10006 Wrong!";
}

HTML5 local storage not storing correctly

I don't know if I have understood the right context of 'storage', but according to some tutorials I used the following Javascript code, to enable a page to locally store (no session) submitted data, but when I close the page and reopen the page, the content do not appear.
script.js
function initiate()
{
var saveButton = document.getElementById('save');
var retrieveButton = document.getElementById('retrieve');
var deleteButton = document.getElementById('delete');
var reviewButton = document.getElementById('review');
saveButton.addEventListener('click', saveItem);
retrieveButton.addEventListener('click', retrieveItem);
deleteButton.addEventListener('click', deleteItem);
reviewButton.addEventListener('click', reviewAll);
}
function saveItem()
{
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage[key] = value;
}
function retrieveItem()
{
var data = document.getElementById('data');
var key = document.getElementById('key').value;
var value = localStorage[key];
data.innerHTML = '<div>' + key + ': ' + value + '</div>';
}
function deleteItem()
{
if (confirm('Delete?'))
{
var key = document.getElementById('key').value;
localStorage.removeItem(key);
data.innerHTML = '<div>Deleted.</div>';
}
}
function reviewAll()
{
for(var i = 0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var value = localStorage[key];
data.innerHTML += '<div>' + key + ': ' + value + '<br></div>';
}
}
addEventListener("load", initiate);
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="mystyles.css" />
<script src="script.js"></script>
<title>Demo HTML5</title>
</head>
<body>
<section id="formSection">
<form name="dataForm">
<label for="key">Key: </label><br />
<input type="text" id="key" name="key" /> <br />
<label for="value">Value: </label><br />
<textarea name="value" id="value"></textarea><br />
<input type="button" id="save" value="Save" />
<input type="button" id="retrieve" value="Retrieve" />
<input type="button" id="delete" value="Delete" />
<input type="button" id="review" value="Review" />
</form>
</section>
<section id="data">
No data
</section>
</body>
</html>
If you are using the browser in privacy mode, it will clear all localStorage data when you close it.

javascript array displaying undefined in text area

So I am working on some home work right now and am having trouble understanding why my array is showing as undefined. Sorry if this is simple, but I am pretty new at this. I will try to explain what I am doing here.
I have three input fields where I gather a students last name, first name and grade. I get all those elements by their id's and put all those inputs into an array called studentGrade. I then push the contents of that array into another array called grades to then pass that as a parameter to a function called get_item_list. from there I try to loop through the contents of that parameter so that I can display it to the text field with the id of "scores".
I really appreciate all the input and hope I can learn what I am doing wrong.
var grades = [];
var $ = function (id) { return document.getElementById(id); }
var update_display = function () {
$("scores").value = get_item_list(grades);
$("last_name").value = "";
$("first_name").value = "";
$("score").value = "";
$("last_name").focus();
}
var student_grade_add_click = function() {
var studentGrade = [];
studentGrade["last_name"] = $("last_name").value;
studentGrade["first_name"] = $("first_name").value;
studentGrade["score"] = parseFloat($("score").value);
if ( studentGrade["last_name"] == "" ) return;
if ( studentGrade["last_name"] == "" ) return;
if ( isNaN(studentGrade["score"]) ) return;
grades.push(studentGrade);
update_display();
}
var get_item_list = function(item_list) {
if ( item_list.length == 0 ) {
return "";
}
var list;
for ( var i in item_list ) {
list += item_list[i] + "\n";
}
return list;
}
window.onload = function () {
$("add_button").onclick = student_grade_add_click;
$("last_name").focus();
}
this is the javascript I am working with
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Student Scores</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript" src="student_scores.js"></script>
</head>
<body>
<div id="content">
<h1>Student Scores</h1>
<div class="formLayout">
<label>Last Name:</label>
<input type="text" id="last_name" /><br />
<label>First Name:</label>
<input type="text" id="first_name" /><br />
<label>Score:</label>
<input type="text" id="score" /><br />
<label> </label>
<input type="button" id="add_button" value="Add Student Score" /><br />
</div>
<h2>Student Scores</h2>
<p><textarea id="scores" rows="5" cols="60"></textarea></p>
<div class="formLayout">
<label>Average score:</label>
<input type="text" id="average_score"/><br />
<label> </label>
<input type="button" id="clear_button" value="Clear Student Scores" /><br />
<label> </label>
<input type="button" id="sort_button" value="Sort By Last Name" /><br />
</div>
</body>
</html>
and there is the html I have made, thanks again.
I think you need to initialize list as a string prior to concatenating values to it:
var get_item_list = function(item_list) {
if ( item_list.length == 0 ) {
return "";
}
var list = "";
for ( var i = 0; i < item_list.length; i++) {
var current = item_list[i];
for ( var attr in current ) {
list += current[attr] + "\n";
}
}
return list;
}
Also, studentGrade is not array, it is an object (even though you are setting keys like an array):
var studentGrade = {};
My changes work, here is your updated fiddle: http://jsfiddle.net/LFhNQ/1/

how to sum radio button values only one time?

I am using this code to sum values from multiple radio buttons :
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
the problem is that when user click on a radio button in a group and then select another radio button in that group the new value will be add to this, i want to only add one of the values to the total value.
for example in this group :
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
when first time a user select seconed radio the 5000 will be add to total price, but if he change it to third option, 15000+5000 will be add to total, i want to have only one of them !
The problem seems, to me, that the total var is declared out of the scope of the change callback. This will cause the closure of the change callback to contain the total variable, so it's value will be persisted across subsequent change calls.
If declare the total within this callback, you should be fine:
$("input[type=radio]").change(function(){
var total = 5000; // => declared locally, so initialized at each change.
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
I wrote a simple example demonstrating this recently (although I did it without using jQuery).
Just store the value you add, and then subtract it from the total before adding a new one.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Radio Test</title>
</head>
<body>
<form action="" method="get" id="myForm">
<fieldset id="myRadioGroup">
<legend>Radios</legend>
<div>
<label> <input type="radio" value="0" name="add" checked> 0 </label>
</div>
<div>
<label> <input type="radio" value="20" name="add"> 20 </label>
</div>
<div>
<label> <input type="radio" value="30" name="add"> 30 </label>
</div>
</fieldset>
<div id="total">45</div>
</form>
<script type="text/javascript">
(function () {
var group = document.forms.myForm.elements.add;
var currentValue = function currentValue () {
for (var i = 0, j = group.length; i < j; i++) {
if (group[i].checked) {
return Number(group[i].value);
}
}
};
var oldValue = currentValue();
var total = document.getElementById('total').firstChild;
var update = function update () {
var current = currentValue();
total.data = Number(total.data) - oldValue + current;
oldValue = current;
};
for (var i = 0, j = group.length; i < j; i++) {
group[i].onchange = update;
}
}());
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>
W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
</body>
<script type="text/javascript">
$(function()
{
$('input:radio').change(function()
{
var total = 50000;
$('input:radio:checked').each(function()
{
if (isNaN(this.value))
total = total;
else
total += parseFloat(this.value);
});
$('.price_amount').text(total);
});
});
</script>
</html>

Categories

Resources