Reputation: 3
I'm doing a website to learn Italian and my problem is when I try to get the answers from a text-box and do the percentage, it always gives me 0% even if i answered them right!
var ri = [ 0, 1, 2, 3, 4];
var res=0;
var rest;
function input(){
ri[0] = document.getElementsByName("r1").value;
ri[1] = document.getElementsByName("r2").value;
ri[2] = document.getElementsByName("r3").value;
ri[3] = document.getElementsByName("r4").value;
ri[4] = document.getElementsByName("r5").value;
checkAnswers();
}
function input(){
if(ri[0]=="abitiamo"){
res=res+1;
}
if(ri[1]=="frequentate"){
res=res+1;
}
if(ri[2]=="suonano"){
res=res+1;
}
if(ri[3]=="trovi"){
res=res+1;
}
if(ri[4]=="studia"){
res=res+1;
}
output();
}
function output(){
rest = res*100/ri.length;
alert(rest+"%");
res=0;
rest=0;
}
<p style="font-size: large;">
1. Noi <input type="text" name="r1" style="width: 86px;"> (abitare) a Roma <br>
2. Che scuola <input type="text" name="r2" style="width: 86px;"> (frequentare) voi, Gianni e Tommaso?<br>
3. Marina e Lucia <input type="text" name="r3" style="width: 86px;"> (suonare) bene il piano. <br>
4. Luca, tu <input type="text" name="r4" style="width: 86px;"> (trovare) delle informazioni interessanti in questa lezione?<br>
5. Luciana <input type="text" name="r5" style="width: 86px;"> (studiare) filosofia a Milano. <br>
</p>
<button onclick="input()">Click me</button>
Upvotes: 0
Views: 96
Reputation: 3844
This is my solution:
var answers = ["abitiamo", "frequentate", "suonano", "trovi", "studia"];
var correctCount = 0;
var result;
function input() {
correctCount = 0;
result=0;
for (i = 0; i < answers.length; i++) {
var textBox = document.getElementsByName("r" + (i + 1))[0];
if (textBox.value == answers[i]) {
correctCount++;
}
}
result = correctCount * 100 / answers.length;
alert(result + "%");
}
<p style="font-size: large;">
1. Noi <input type="text" name="r1" style="width: 86px;"> (abitare) a Roma <br>
2. Che scuola <input type="text" name="r2" style="width: 86px;"> (frequentare) voi, Gianni e Tommaso?<br>
3. Marina e Lucia <input type="text" name="r3" style="width: 86px;"> (suonare) bene il piano. <br>
4. Luca, tu <input type="text" name="r4" style="width: 86px;"> (trovare) delle informazioni interessanti in questa lezione?<br>
5. Luciana <input type="text" name="r5" style="width: 86px;"> (studiare) filosofia a Milano. <br>
</p>
<button onclick="input()">Click me</button>
Upvotes: 1