0

I have a 3 question quiz that I made. I just cant figure out the rest of the Javascript code that I need to use. Once submitting the quiz, it needs to validate that all questions have answers (I dont wanna use alert or prompt saying you didnt do this or that --> I wanna style it with like displaying a red asterisk next to it. After it is answered I would like it to display the number of correct answers. Example: I get 2 out of 3 right. It will display I got 2 right (I wanna would like to use appendChild) Here is how I have it set up so far:

<!DOCTYPE html>
<html>
<head>
<title>Quiz</title>
<meta charset="utf-8">

</head>
<body>

<form action="" method="post" onsubmit="return FormValidation()";>

<div class="question1">
    1) What is your first name?<br/>
    <input type="text" id="firstname" name="name"/><br/><br/>
</div>

<div class="question2">
    2) What is 5 + 5?<br/><br/>
    <input type="radio" id="10" name="10"/>10
    <input type="radio" id="10" name="9"/>9
    <input type="radio" id="10" name="11"/>11
</div><br/><br/>

<div class="question3">
    3) What happened a long time ago in a galaxy far far away?<br/><br/>
    <select>
        <option value="hp">Harry Potter</option>
        <option value="twi">Twilight</option>
        <option value="star">Star Wars</option>
    </select>
</div><br/><br/>


</form>

<script>
function FormValidation(){
var fn=document.getElementById('firstname').value;
if(fn == ""){
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}

}
</script>

</body>
</html>
Chad
  • 9
  • 5

1 Answers1

0

I just looked at this: javascript validation for empty input field Give your form a name attribute, and your input fields name attributes as well, then you can do something like var a=document.forms["Form"]["ans_a"].value; and check with

if(a===null){
//apply your style with a red asterisk here, or append a red asterisk element
}

You can also determine how many they got right with this approach,

var expectedAnswer1 = "George Washington"
if(a===expectedAnswer1){
    correctAnswerCount++
}
Community
  • 1
  • 1