I tried writing a code for the above image forming a question and list of options with radio button. If user selects the correct answer the message should display as " answer : correct " and " answer : incorrect " for wrong answer i tried until this and if user doesn’t select any option and clicks on submit button it should display message as "please select any option". I tried writing code for that like this in html and javascript but i am not getting output. Can anyone help me with this
function answer() {
var ans = document.getElementById("ans3")
var status1 = ans.checked
var btn2 = document.getElementById("button1")
if (status1 == true) {
document.getElementById("lab").innerHTML = "answer : correct"
} else {
document.getElementById("lab").innerHTML = "answer : incorrect "
}
}
function disp() {
var click = document.getElementById("button1").value
if (click == "") {
document.getElementById("lab2").innerHTML = "answer: please select any option"
}
}
disp()
<form>
<center>
<div style="background-color:slateblue; width:70%; height:530px;">
<br></br>
<input placeholder="enter email" type="text" id="finp" onkeyup="dis()"></input>
<br></br>
<input placeholder="enter password" disabled type="password" id="sinp" onkeyup="dis1()"></input>
<br></br>
<input type="button" value="Login" disabled id="btn"></input>
<br></br>
<hr></hr>
<h2 style="color:white;"> In which tag <Script> tag should be specified ?</h2>
<br></br>
<input type="radio" name="abc" id="ans1"> <strong style="color:white;"><Head> </strong></input>
<br></br>
<input type="radio" name="abc"><strong style="color:white;"> <Body> </strong></input>
<br></br>
<input type="radio" name="abc" id="ans3"> <strong style="color:white;">Both <Body> and <Head> </strong></input>
<br></br>
<input type="radio" name="abc"><strong style="color:white;"> None of the above</strong> </input>
<br></br>
<strong style="color:white;" id="lab">answer : </strong>
<strong style="color:white;" id="lab2"></strong>
<br></br>
<input type="button" value="submit" id="button1" onclick="answer()"></input>
</div>
</center>
</form>
3
Answers
several little things to change to make running your code :
var click = document.getElementById("button1").value
you will get the value of the button and not the fact if form have been reply or not -> for this part i can propose you to store form state in a variable (in my sample i just declare status1 as a global variable)lab
div but you stored your reply inlab2
i just change the selectorYou can use the Form API to check if there is a selected value for any elements with the name set to
abc
. If it is an empty string, then there is nothing selected.Also, I do not recommend giving radio buttons IDs, because they are grouped together by name anyways. Instead, give the correct radio button an attribute such as
data-correct
. Then, just map through them and see if the selected one is correct or not based on its presence.