Trying to get back a score from a quiz - javascript

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.

Related

Scoring system for a quiz

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
}

js crossing two function

I'm beginer in js, please help me.
I have two functions. First function sum all checked input ticket and view sum price, secondary function check discount code and takes into account the new price.
The problem is when I add a discount code and then will choose a ticket. Then it does not calculate the value.
https://jsfiddle.net/wznvfkm3/
$('.participantEventTicket').on('change', function() {
var totalPrice = 0.00;
$('.participantEventTicket:checked').each(function() {
totalPrice += parseFloat($(this).data('price'), 10);
});
$('.participantEventTicketSum').html(totalPrice.toFixed(2));
$('.participantEventTicketDiscountValueTotal').html(totalPrice);
});
$('.participantEventTicketDiscount').on('change', function() {
var code = ($(this).val());
var valueTotal = document.getElementById('participantEventTicketSum').innerHTML;
var value = 0;
var liste = [];
liste[0] = ['ABB'], -5]; liste[1] = ['BBC'], -10];
for (var i = 0, len = liste.length; i < len; i++) {
if (liste[i][0] === code) {
var value = liste[i][1];
}
}
var valueTotalS = parseInt(valueTotal) + parseFloat(value);
$('#participantEventTicketDiscountValue').html(value.toFixed(2));
$('#participantEventTicketDiscountValueTotal').html(valueTotalS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ticket 1
<input type="checkbox" name="participantEventTicket[]" value="5" class="participantEventTicket" />
<br/>ticket 2
<input type="checkbox" name="participantEventTicket[]" value="10" class="participantEventTicket" />
<br/>Sume tickets: <span class="participantEventTicketSum" id="participantEventTicketSum">0.00</span>
<br/>Discount coupon
<input type="text" id="participantEventTicketDiscount" class="participantEventTicketDiscount">
<br/>Discount value <span id="participantEventTicketDiscountValue" class="participantEventTicketDiscountValue">0.00</span>
<br/>Discount value sum <span id="participantEventTicketDiscountValueTotal" class="participantEventTicketDiscountValueTotal">0.00</span>
</form>
Slawotu,
Please check this fiddle
You had couple errors:
$('.participantEventTicket:checked').each(function () { totalPrice += parseFloat($(this).val(), 10);});
// you supposed to take $(this).val()
You didn't put calculation of total Price when you entered discount and changed you ticket:
$('.participantEventTicketDiscountValueTotal').html(totalPrice + value);
Forgot but brackets:
liste[0] = [['ABB'], -5];
liste[1] = [['BBC'], -10];
You compared 2 different objects using === instead use ==
if (liste[i][0] == code)
Declare val on top of the file, don't declare inside if statement.
var value = 0;

Loop Over Input Fields; Stop After Two Iterations

I have five form fields that will initially NOT be pre-populated with any values.
If a user fills out one of the fields, the next time they visit the form that field will be pre-populated with the value from the previous visit.
Here's what I'm trying: I'd like to create a loop that iterates through the fields. It will always check to see if there are empty fields. After finding 2 empty fields, the loop will stop and only show those 2 empty fields, while the other fields are hidden.
Here's what I have so far...I just can't figure how to stop after iterating through two fields,
HTML:
<form action="">
<input id="first" type="text" value="" />
<input id="second" type="text" value="" />
<input id="third" type="text" value="" />
<input id="fourth" type="text" value="" />
<input id="fifth" type="text" value="" />
</form>
JS:
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
for (var i = 0; i < fieldIds.length; i++) {
for (var i = 0; i < formValues.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
return false;
}
}
}
});
Take all input fields, take the first two empty fields and show them; finally, take the complement of that to hide the rest:
var $inputFields = $('form input:text'),
$emptyFields = $inputFields
.filter(function() { return this.value == ''; })
.slice(0, 2)
.show();
$inputFields
.not($emptyFields)
.hide();
Demo
$(document).ready(function() {
$('input').hide().each( function(){
var index=0; //initilialize the counter
if( $(this).val().length ){ //check for input's length
if(index < 2) {
$(this).show();
index=index+1 //or index++ if you like
}
else {
break;
}
}
}
)};
If you want to include select and textarea fields in your eligible input population, use $(':input').hide().each(...). If you have multiple forms on your page, you would want to include that in your selector, too: $('#intended_form').find(':input').hide().each(...).
http://api.jquery.com/each/
I think that Jack provides the best answer, but this should work too. here, i use a second counter j and break the loop when j % 2 == 0, so at this time its found two empty fields. this is known as a modulus or the modulo operator.
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
var j = 0;
for (var i = 1; i < fieldIds.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
j++;//we found an empty field
if (j % 2 == 0)
{
break;
}
}
}
});

Connect MySQL Database with Javascript Quiz (Beginner)

I am building a quiz, I have constructed the database (I will input an example of what my tables look like below. I am having an issue getting the user's answers to actually be placed in the database? Right now, I can load the quiz on my browser, answer the questions, but I cannot actually figure out my score on the quiz.
Database
questions
ID question
1 Question1?
2 Question2?
etc
choices
ID questID answer
1 1 Ansa
2 1 Ansb
3 1 Ansc
1 2 Ansa
2 2 Ansb
3 2 Ansc
4 2 Ansd
etc
userans
userID questID answerID
right now userans table is empty because that is where the user's answers are supposed to be put
My quiz is pretty simple, but I just need help getting the database & quiz to "talk" to each other.
Any help is appreciated!
Quiz code
<!DOCTYPE html>
<html>
<head>
<title>Quiz</title>
<script language="Javascript">
function process()
{
var A = 0;
var B = 0;
var C = 0;
var D = 0;
var f = document.f;
var i = 0;
for (i = 0; i < f.q1.length; i++) if (f.q1[i].checked) value = f.q1[i].value;
if (value == "13") { }
if (value == "11") { C++; A++; B++; }
if (value == "5") { C++; D++; A++; B++; }
for (i = 0; i < f.q2.length; i++) if (f.q2[i].checked) value = f.q2[i].value;
if (value == "5") { C++; D++; A++; B++; }
if (value == "12") { D++; A++; B++; }
if (value == "11") { C++; A++; B++; }
if (value == "10") { C++; D++; A++; }
/*Copy the above for loop for all subsequent questions, if needed*/
var out = "A";
i = "a";
if (C > i) { out ="C"; i = "c"; }
if (B > i) { out ="B"; i = "b"; }
if (D > i) { out ="D"; i = "d"; }
window.alert ("Result: " + i + " !!");
}
</script>
</head>
<body>
<?php include ('Menu2.html'); ?>
<p>Answer the questions below</p> <br>
<form name="f">
<b>Question1<br></b>
<input type="radio" name="q1" value="1">Ansa<br>
<input type="radio" name="q1" value="2">Ansb<br>
<input type="radio" name="q1" value="3">Ansc<br><br>
<b>Question2<br></b>
<input type="radio" name="q2" value="1">Ansa<br>
<input type="radio" name="q2" value="2">Ansb<br>
<input type="radio" name="q2" value="3">Ansc<br>
<input type="radio" name="q2" value="4">Ansd<br><br>
/*Input more questions, if needed, here*/
Thanks for taking the quiz! <br>
<input type="button" value="Score!" onclick="process();"><br><br>
</form>
</body>
</html>
Javascript is a client side language - in order to connect to a database, you'll need to use server side software such as PHP. Your HTML form can submit content via GET or POST, or you can use Ajax to push/pull information, but cannot be done via Javascript.
Check out some examples:
Can JavaScript connect with MySQL?
How can I use jQuery to run MySQL queries?

Javascript Internet Explorer Issue - what am I doing wrong?

I've looked through many posts to no avail. I have the following in a simple form where one of the products changes based on the number of checkboxes checked. It works in every browser except IE. What am I doing wrong?
<body>
<script type="text/javascript">
function check(){
"use strict";
var count = 0, x=0, checkboxes=document.signup.getElementsByClassName("styled");
for(;x<checkboxes.length; x++){
if(checkboxes[x].checked){
count++;
}
}
if(count<3) {
document.getElementById("variable").value = "1";
}
else if (count == 3){
document.getElementById("variable").value = "74";
}
else if (count == 4){
document.getElementById("variable").value = "75";
}
else if (count == 5){
document.getElementById("variable").value = "76";
}
}
</script>
<form name="signup" id="signup" method="post" action="/subscribers/signup.php">
<input type="checkbox" id="variable" name="product_id[]" value="" class="styled"></input>product 1 - variable</div>
<input type="checkbox" id="same" name="product_id[]" value="3" class="styled"></input>product 2
<input type="checkbox" id="same2" name="product_id[]" value="2" class="styled"></input>product 3
<input type="checkbox" id="same3" name="product_id[]" value="4" class="styled"></input><div class="check-title">product 4
<input type="checkbox" id="same4" name="product_id[]" value="44" class="styled"></input><div class="check-title">product 5
Continue</td></tr>
</form>
</body>
All versions of IE prior to IE9 do not support getElementsByClassName(). You will need to use some sort of substitute.
Instead of this piece of your code:
checkboxes = document.signup.getElementsByClassName("styled");
I would suggest using this:
checkboxes = document.getElementById("signup").getElementsByTagName("input")
getElementsByTagName() is widely support in all versions of IE. This will obviously get all input tags, but only the checkboxes will have checked set so you should be OK.
If you need to filter by class, then you could do the whole thing this way:
function check() {
"use strict";
// initialize checkbox count to 0
var count = 0, item;
// get all input tags in the form
var inputs = document.getElementById("signup").getElementsByTagName("input");
// loop through all input tags in the form
for (var i = 0; i < inputs.length; i++) {
// get this one into the local variable item
item = inputs[i];
// if this input tag has the right classname and is checked, increment the count
if ((item.className.indexOf("styled") != -1) && item.checked) {
count++;
}
}
// get object for result
var obj = document.getElementById("variable");
// check count and set result based on the count
if(count < 3) {
obj.value = "1";
} else if (count == 3) {
obj.value = "74";
} else if (count == 4) {
obj.value = "75";
} else if (count == 5) {
obj.value = "76";
}
}
IE doesnt have method getElementsByClassName... you can try to define it:
if(document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
retnode.push(elem[i]);
}
}
return retnode;
}
};

Categories