How do I get the scoring system to work right?
It adds +1 if it's correct, but + an even bigger number if it's wrong...I just want it to add +1 to both.
It should post only +1 for wrong...
HTML
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question1' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question2' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question3' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question4' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question5' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question6' id='question6'>
</h5>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question7' id='question7'>
</div>
<button id='button' type='button' onclick='answer()'>Do you even anime?</button>
</form>
<span class='correct'>
<label for='score'>CORRECT</label>
<input type='text' id='score'>
</span>
<span class='wrong'>
<label for='wrong'>WRONG</label>
<input type='text' id='wrong'>
</span>
JavaScript:
var quizArray = [
{ answer: 'ashente' },
{ answer: 'green' },
{ answer: 'yes' },
{ answer: 'love' },
{ answer: 'both' },
{ answer: 'chopper' },
{ answer: 'heavens' }
]
function answer() {
var correct = 0;
var wrong = 0;
for (i = 0; i < quizArray.length; i++) {
var question1 = document.getElementById('question1').value;
if (question1 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question3 = document.getElementById('question3').value;
for (i = 0; i < quizArray.length; i++) {
if (question3 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question4 = document.getElementById('question4').value;
for (i = 0; i < quizArray.length; i++) {
if (question4 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question5 = document.getElementById('question5').value;
for (i = 0; i < quizArray.length; i++) {
if (question5 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question6 = document.getElementById('question6').value;
for (i = 0; i < quizArray.length; i++) {
if (question6 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question7 = document.getElementById('question7').value;
for (i = 0; i < quizArray.length; i++) {
if (question7 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
Here it is. You have several problems. Check teh code and feel free to ask anything:
var quizArray = [{
answer: 'ashente'
}, {
answer: 'green'
}, {
answer: 'yes'
}, {
answer: 'love'
}, {
answer: 'both'
}, {
answer: 'chopper'
}, {
answer: 'heavens'
}]
function answer() {
var correct = 0;
var wrong = 0;
var questions = document.querySelectorAll(".question");
for (i = 0; i < quizArray.length; i++) {
if (questions[i].value.toLowerCase() == quizArray[i].answer.toLowerCase()) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
(function(){
document.getElementById("button").addEventListener("click", answer);
})();
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question' id='question6'>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question' id='question7'>
</div>
<input id='button' type='submit' value="Do you even anime?">
<span class='correct'><label for='score'>CORRECT</label><input type='text' id='score'></span>
<span class='wrong'><label for='wrong'>WRONG</label><input type='text' id='wrong'></span>
I will calrify some points anyway. As you could see, the main difference is the size of the js. You had teh same piece of code for each question, when you are in a situation like this, you should use a function or a loop. This is part of the DRY concept. So taking all the questions in an array and iterate over them is easier than create a piece of code for each one.
I added the function toLowerCase because is annoying failing answers only if you missed that detail. Using this function is not necessary, it's up to you.
In the HTML part I must remark that if you have a button that sends a form you should create an input which type is submit. HTML button is not properly for submitting a form. It can do the job, but it is not the correct way.
You use inputs to show the score, but, instead it will be better to use plain text. Again, it's not bad but it's handier.
The issue is related to how the incrementing is implemented in the for-loops. Let's take the first loop as an example:
You are trying to assess whether or not question 1 has been answered correctly by comparing the users answer with every possible answer in the quizArray element. With 7 questions we should have 7 iterations of the loop. In each iteration, you check if the answer for question 1 is correct and increment the correct variable accordingly. Otherwise you increment the wrong variable. So for 7 iterations of the for-loop you are incrementing the wrong variable at least 6 times.
Instead of trying to increment the correct and wrong variables in each iteration, you can use a flag to determine if the question was answered correctly, and then increment the variables after the loop. For example:
var correct = 0;
var wrong = 0;
var question1 = document.getElementById('question1').value;
var answerCorrect = false;
for (i = 0; i < quizArray.length; i++) {
if (question1 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
answerCorrect = false;
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
Related
For some reason only the score0 wants to increment. Although the two for-loops seem identical (really sorry if I'm wrong). So the totScore just gets the value from the score0 variable. But ofcourse I want totScore to get value form both variables so to get the total score of the quiz.
Also, why does it add 4 to the score0 variable when I wrote score0 += 1;, that doesn't make any sence to me.
If you change my code alot please don't use any JQuery.
Thanks!
<!DOCTYPE html>
<html>
<body>
<form id='quizForm'>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0" value="A" />2<br>
<input type="radio" name="question0" value="B" />1<br>
<input type="radio" name="question0" value="C" />3<br>
<input type="radio" name="question0" value="D" />4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1" value="A" />2<br>
<input type="radio" name="question1" value="B" />1<br>
<input type="radio" name="question1" value="C" />3<br>
<input type="radio" name="question1" value="D" />4<br>
</li>
</ul>
</form>
<button onclick="showScore()">Show results
</button>
<script>
//Score and answer variables
var score1 = 0;
var score0 = 0;
var totScore = 0;
var answers = ["A","C"]
//function to calculate the score.
function getScore() {
// some arrays and stuff
userInput1 = new Array(10);
userInput0 = new Array(10);
var question0s = document.getElementsByName("question0");
//for loop to see which radio was checked
for (var i = 0; i < question0s.length; i++) {
if (question0s[i].checked) {
userInput0[0] = question0s[i].value;
}
if (userInput0[0] == answers[0]) {
// Only god knows why the hell I have to divide 4
score0 += 1 / 4;
}
else if (userInput0[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score0 -= 1 ;
}
}
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
if (score0 < 0){
score0 = score0 * 0;
}
var question1s = document.getElementsByName("question1");
//for loop to see which radio was checked
for (var y = 0; y < question1s.length; y++) {
if (question1s[y].checked) {
userInput1[0] = question1[y].value;
}
if (userInput1[0] == answers[0]) {
score1 += 1;
}
else if (userInput1[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score1 -= 1 ;
}
}
if (score1 < 0){
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
score1 = score1 * 0;
}
//getting score from all different questions
totScore += score1 + score0;
}
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function(){
getScore();
});
// onclick function
function showScore (){
alert (totScore);
}
</script>
</body>
</html>
As to why you are not getting proper processing, you have an invalid variable question1 here:
userInput1[0] = question1[y].value;
Now let's fix this and do better.
First off, you have a number of global variables so let's get that under a simple namespace and call it quiz.
Get the click handler out of the markup and create a listener for that.
Now as for your logic, you are looping through the radio buttons. Now the way radio buttons work is that only one can be selected SO, let's use that to our advantage an not do the loop at all.
With the radio buttons, if one is NOT selected yet, then it will be NULL using our new selection technique so we can use that to tell if both the questions have been answered and then if that IS true, we can put scores in. Otherwise, they get no score (score is 0) until all the questions ARE answered (not NULL).
//Score and answer variables=
var quiz = {
score0: 0,
score1: 0,
totalScore: 0,
answers: ["A", "C"],
maxScore: 2,
tries: 0
};
//function to calculate the score.
function getScore() {
var answer0 = document.querySelector('input[name="question0"]:checked');
quiz.score0 = answer0 != null && quiz.answers[0] == answer0.value ? 1 : 0;
var answer1 = document.querySelector('input[name="question1"]:checked');
quiz.score1 = answer1 != null && quiz.answers[1] == answer1.value ? 1 : 0;
// if either is null, not all answered
if (answer0 != null && answer1 != null) {
// if previous tries, subtract how many
if (quiz.tries) {
quiz.totalScore = quiz.totalScore ? quiz.totalScore - quiz.tries : 0;
quiz.totalScore = quiz.totalScore < 0 ? 0 : quiz.totalScore ;//0 if negative
} else {
quiz.totalScore = quiz.score1 + quiz.score0;
}
quiz.tries++;
}
}
// onclick function
function showScore() {
alert(quiz.totalScore + " in tries: " + quiz.tries);
}
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
showScore();
});
Try the above out here: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/2/
You could also do more with this by putting that in the quiz something like this:
//Score and answer variables=
var quiz = {
totalScore: 0,
tries: 0,
maxScore: 2,
answered: 0,
questions: [{
question: {},
name: "question0",
score: 0,
answer: "A"
}, {
question: {},
name: "question1",
score: 0,
answer: "C"
}],
checkQuestion: function(q) {
q.score = q.question != null && q.answer == q.question.value ? 1 : 0;
},
//function to calculate the score.
getScore: function() {
this.answered = 0;
for (var i = 0; i < this.questions.length; i++) {
var sel = 'input[name="' + this.questions[i].name + '"]:checked';
this.questions[i].question = document.querySelector(sel);
this.checkQuestion(this.questions[i]);
this.answered = this.questions[i].question ? this.answered + 1 : this.answered;
}
console.dir(this);
// if either is null, not all answered
if (this.answered == this.questions.length) {
for (var i = 0; i < this.questions.length; i++) {
this.totalScore = this.totalScore + this.questions[i].score;
}
if (this.tries) {
this.totalScore = this.tries && this.totalScore ? this.totalScore - this.tries : 0;
this.totalScore = this.totalScore < 0 ? 0 : this.totalScore; //0 if negative
}
this.tries++;
}
},
// onclick function
showScore: function() {
var t = "";
if (this.answered != this.questions.length) {
t = "Not all questions ansered!"
} else {
t = this.totalScore + " in tries: " + this.tries;
}
alert(t);
}
};
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
quiz.getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
quiz.showScore();
});
Second example in action: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/4/
Well if you want to simply get the result from the test, use this code:
<!DOCTYPE html>
<html>
<body>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0"/>1<br>
<input type="radio" name="question0"/>2<br>
<input type="radio" name="question0"/>3<br>
<input type="radio" name="question0"/>4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1"/>1<br>
<input type="radio" name="question1"/>2<br>
<input type="radio" name="question1"/>3<br>
<input type="radio" name="question1"/>4<br>
</li>
</ul>
<button onclick="calculate()">Submit</button>
<script>
function calculate(){
var answers = [1, 2];
var score = 0;
var question0s = document.getElementsByName("question0");
var question1s = document.getElementsByName("question1");
if (question0s[answers[0]].checked == true) {
score++;
}
if (question1s[answers[1]].checked == true) {
score++;
}
alert ("You got " + score + " out of " + answers.length + ".");
}
</script>
</body>
</html>
It looks like you're calling the script every time an answer changes, and this is very inefficient. I'm only calling when all the answers have been made and the user presses submit.
And the reason why that is adding 4 times is because if you set your first answer to A, it writes it to userinput0 and doesn't get changed anymore since the answer was the only one checked, and it repeats the amount of choices there are, in which there were 4. Thus you are repeating that assignment statement 4 times so you are adding 4.
I have a little product search code that I've been working on for a while. It works great, although a bit backwards.
The more keywords I type in, ideally, the less products will show up (because it narrows down the results). But as is stands, the more keywords I type in my search system, the MORE products are displayed, because it looks for any product with any of the keywords.
I want to change the script so that it only shows results if they include ALL the searched for keywords, not ANY of them...
Sorry for the long-winded explanation.
Here's the meat and potatoes (jsfiddle):
http://jsfiddle.net/yk0Lhneg/
HTML:
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
JAVASCRIPT:
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].style.display = "block";
}
}
}
}
}
So, when you search "mac pc" the only result that should be displayed is the hybrid, because it has both of those keywords. Not all 3 products.
Thank you in advance!
I changed a little bit your code to adjust it better to my solution. I hope you don't mind. You loop first over the terms, and then through the list of products, I do it the other way around.
How this solution works:
Traverse the list of products, for each product:
Create a counter and set it to 0.
Traverse the list of search terms, for each.
If the word is found in the product's name, add 1 to the counter.
If the counter has the same value as the list length, display the product (matched all words)
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
// I moved this loop outside
var nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
// set a counter to zero
var num = 0;
// I moved this loop inside
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
// only run the search if the text input is not empty (to avoid a blank)
if (str_needle !== "") {
// if the term is found, add 1 to the counter
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
num++;
}
// display only if all the terms where found
if (num == searchStrings.length) {
nameDivs[j].style.display = "block";
}
}
}
}
}
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
You can also see it on this version of your JSFiddle: http://jsfiddle.net/yk0Lhneg/1/
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I added the alert to test if the script was working at all, once i deleted the function it did, but once I add the function the html doesn't even show the alert. I tried loading the code in a different file and calling it in the head, the body, for some reason the code won't even load much less can i get the button at the end to work.
<!DOCTYPE html>
<html>
<head>
<title> Astronomy Quiz </title>
</head>
<body>
<div>
<script>
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
</script>
<center>
<h1> Astronomy Quiz </h1>
</center>
<h3> True / False </h3>
<form id = "quiz">
<label><b>1)</b> According to Kepler the orbit of the earth is a circle with
the sun at the center.
<input type = "radio" name = "q1" value = "True" />
True
<input type = "radio" name = "q1" value = "False" />
False</label>
<br>
<br>
<label><b>2)</b> Ancient astronomers did consider the heliocentric model of
the solar system but rejected it because they could not detect parallax.
<input type = "radio" name = "q2" value = "True" />
True
<input type = "radio" name = "q2" value = "True" />
False</label>
<br>
<h3> Multiple Choice </h3>
<b>3)</b> The total amount of energy that a star emits is directly related
to its
<br>
<input type = "checkbox" name = "q3" value = "a" />
a) surface gravity and magnetic field
<br>
<input type = "checkbox" name = "q3" value = "b" />
b) radius and temperature
<br>
<input type = "checkbox" name = "q3" value = "c" />
c) pressure and volume
<br>
<input type = "checkbox" name = "q3" value = "d" />
d) location and velocity
<br>
<br>
<b>4)</b> Stars that live the longest have
<br>
<input type = "checkbox" name = "q4" value = "a" />
a) high mass
<br>
<input type = "checkbox" name = "q4" value = "b" />
b) high temperature
<br>
<input type = "checkbox" name = "q4" value = "c" />
c) lots of hydrogen
<br>
<input type = "checkbox" name = "q4" value = "d" />
d) small mass
<br>
<h3> Fill in the Blank </h3>
<label><b>5)</b> A collection of a hundred billion stars, gas, and dust is
called a
<input type = "text" name = "q5" value = "" size = "15" />
.</label>
<br>
<br>
<label><b>6)</b> The inverse of the Hubble's constant is a measure of the
<input type = "text" name = "q6" value = "" size = "15" />
of the universe.</label>
<br>
<br />
<input type = "button" value = "Grade" onclick = "quiz()" />
<input type = "reset" name = "Clear" value = "Clear" />
</form>
</div>
</body>
</html>
Try this out:- http://jsfiddle.net/adiioo7/fDDCW/
JS:-
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
on line 88:
if(get.q6.value.match(/^age$/i))
you missed ) in your javascript...
You have missed a ) here:
if(get.q6.value.match(/^age$/i)
Change this to:
if(get.q6.value.match(/^age$/i))
if (get.q6.value.match(/^age$/i) {
This like is missing a closing )
Try this:
if (get.q6.value.match(/^age$/i)) {
To find what's wrong with your JavaScript code use try-catch as follows-
<script>
try
{
/*some JS code*/
}
catch(foo)//Use any variable in place of foo
{
alert(foo);
}
</script>
This will definitely not correct the error but may help you much to find what the error is. Though this is not an answer but you may follow this approach globally anywhere anytime.
There is something in this javascript or html which is is allowing the checkboxes to be ticked but for not even half a second. (I need the checks to stay there!) I also need the additems function to work
var computer = new Array();
computer[0] = "10001, Nvidia Geforce GTX 690, 1200";
computer[1] = "10002, Raedon HD 7950, 450";
computer[2] = "20001, Ivy Bridge i7 3770, 400";
computer[3] = "20002, Ivy Bridge i7 3770k, 420";
computer[4] = "20003, Sandy Bridge i7 2700k, 340";
computer[5] = "20004, Bulldozer FX-8150, 270";
computer[6] = "30001, Antec eleven-hundred, 120";
computer[7] = "30002, Coolermaster HAF-X, 170";
computer[8] = "30003, Antec three-hundred, 50";
computer[9] = "30004, Corsair 550D, 160";
computer[10] = "40001, INTEL-ASrock fatal1ty Z77 Professional Motherboard, 250";
computer[11] = "40002, INTEL-ASrock Z77 extreme9 Motherboard, 350";
computer[12] = "40003, AMD-ASrock fatal1ty 990FX Professional Motherboard, 240";
computer[13] = "40004, AMD-ASUS Sabertooth 990FX Motherboard, 260";
Check all checkboxes function
function check() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 1;
} else {
inputs[x].checked = true;
}
}
}
Uncheck all checkboxes function
function uncheck() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 0;
} else {
inputs[x].checked = false;
}
}
}
add checked items to cart
function addItems() {
var leftSide = document.getElementById('table_container_left');
var rightSide = document.getElementById('table_container_right');
var inputs = leftSide.getElementByTagName('input');
var totalPrice = 0;
var basketTable = "<h3>My Basket:</h3><table><thead><tr><th>Item</th><th>Quantity</th><th>price</th><th>Sub-total</th></tr></thead><tbody>";
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].checked == true) {
var quantity = ParseFloat(inputs[x+1).value);
var itemName = computer[x/2].split(",")[1];
var itemPrice = parseFloat(computer[x/2].split(",")[2])
var itemTotal = parseFloat(quantity*itemPrice);
totalPrice += itemTotal;
basketTable += "<tr><td>"+itemName+"</td><td>"+quantity+"</td><td>$"+itemPrice+"</td><td>$"+itemTotal+"</td></tr>";
}
}
basketTable +=" <tr><td> colspan='3'><b>Total:</b></td><td><b>$"+totalPrice+"</b></td></tr></tbody><table>";
rightsSide.innerHTML = basketTable;
}
update quantity to 1 when item is checked
function updateQty(id) {
var targetRow = document.getElementById(id);
var qtyBox = targetRow.getElementsByTagName('input')[1];
if (qtyBox.value == 0) {
qtyBox.value = 1;
} else {
qtyBox.value = 0;
}
}
Here's the HTML as requested
<form name="myForm" action="index.html" method="post">
<div id="table_container_left">
<button onclick="check();">Select All</button>
<button onclick="uncheck();">Unselect All</button>
<button onclick="addItems();">Add Items</button>
<table>
<thead>
<th><u>Item Code</u></th>
<th><u>Item</u></th>
<th><u>Qty</u></th>
<th><u>Price</u></th>
</thead>
<tbody>
<script type="text/javascript">
for(x=0; x<=computer.length-1; x++) {
document.write("<tr id='"+x+"'><td><label><input type='checkbox' name='item' value='"+x+"' onclick='updateQty('"+x+"');'/> "+computer[x].split(",")[0]+"</label></td><td>"+computer[x].split (",")[1]+"</td><td> <input name='qty' id='qty' type='textbox' value='0' onchange='qtychange ('"+x+"');'/></td><td>$"+computer[x].split(",")[2]+"</td></tr>");
}
</script>
</tbody>
</table>
</div>
<div id="table_container_right">
<table id="shoppingBasket">
<input name='selectAll' type='button' value='Select All' onclick="itemSelected();"/>
<input name='clearAll' type='button' value='Clear All' onclick=""/>
<input name='removeItem(s)' type='button' value='Remove Item(s)' />
<input name='sortItemCode' type='button' value='Sort by Item Code' disabled='disabled' />
<input name='sortPrice' type='button' value='Sort by Price' disabled='disabled' />
</tbody>
</table>
</div>
</div>
</form>
Your JS syntax is way off, this is what it should look like
function addItems(field) {
for (i = 0; i <= field.length-1; i++)
{
if (field[i].checked == true)
{
if (computer[i]!=null) {
selected[i] = computer[i];
}
}
}
}
Half of your if statements are missing parentheses, that's some basic wrongfulness.
I don't know what and where should any of the variables be, but here is my best shot:
function addItems(field) {
var i;
for (i = 0; i < field.length; i++) {
if (field[i].checked === true) {
if (computer[i] !== null) {
selected[i] = computer[i];
}
}
}
}
You are using i = 0 rather than var i = 0, which will introduce a global variable. This could be a problem if you're writing similar code elsewhere.
Your if-statements are not statements at all. They look like pseudo-code. You're also comparing with = rather than ==, which will cause an assignment rather than a condition, even if you fix up your syntax.
You are not properly indenting your code, which will make you much more prone to introduce new errors.
These are the general issues I notice immediately. Of course, heaps of things could be wrong with this code. fields might not be an array, computer and selected might not match the size of fields, etc.
If you have any specific problem, please describe that, and we may be able to address it.
So im trying to perform a basic validation to check if a field is empty. I want to do it in a loop..
<input type="text" size="25" name="q170_Name" class="text" value="" id="q170" maxlength="100" maxsize="100" />
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"];
var totalz = (dropdowns.length);
//loop through the array
for ( var i in dropdowns ) {
if (document.getElementById(dropdowns[i]) == "") {
alert('missed one!');
}}}
I appreciate the help
if (document.getElementById(dropdowns[i]).value == "") {
alert('missed one!');
--edit
but probably there is a better way to do this:
for (var i = 0; i < document.myFormName.length; ++i) {
if( document.myFormName.elements[i].type == "text" &&
document.myFormName.elements[i].value == "") {
alert('missed one!');
}
}
I recommend you to do a simple for loop since for..in is meant to iterate over object properties, also note that you need to check the value attribute of the fields:
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"],
totalz = dropdowns.length,
i;
for (i = 0; i < totalz; i++) {
if (document.getElementById(dropdowns[i]).value == "") {
alert('Check the value of ' + dropdowns[i]);
}
}
}