Creating a multiple choice option in javascript - javascript

I have created an HTML multiple choice question. I am facing a problem how to validate it. Below is the HTML code:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
When the user clicks the submit button, there should be an alert that will show a message based on what was selected.
If no option was selected, the alert box should say "please select choice answer".
If the "Scripting" option was selected, the alert box should say "Answer is correct !"
If an option different from "Scripting" is selected, the alert box should say "Answer is wrong".
I want to create this validation in JavaScript.

You have to use onclick attribute and more js
attach event hander to your button
get radio elements value
compare
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>

var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
Some changes
I made some changes to the code above to make it more 'abstract'
<h1>JavaScript is ______ Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer(d1.choice.value, 'Scripting')">Submit Answer</button>
<script>
var submitAnswer = function(valore, rightanswer) {
if (valore == rightanswer) {
alert("OK");
}
};
</script>
Another, more complex example
<div style="background-color:lightblue">
<h1>JavaScript is a <span id='a1'>______</span> Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Scripting', 'd1','a1')">
</form>
</div>
<div style="background-color:lightblue">
<h1>Python is a <span id='a2'>______</span> Language.</h1><br>
<form id="d2">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Wonderful"> Wonderful
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Wonderful', 'd2', 'a2')">
</form>
</div>
<script>
var validate = function(valore, rightanswer, form, span) {
var formname = document.getElementById(form)
var spanname = document.getElementById(span)
spanname.innerHTML = rightanswer;
if (valore == rightanswer) {
formname.innerHTML ="<div style='background-color:lightgreen'><h1>GREAT! YOU'RE RIGHT: The answer, in fact, was: " + rightanswer + "</h1></div>";
}
else {
formname.innerHTML ="<div style='background-color:pink'><h1>Sorry, you where wrong: The answer was: " + rightanswer + "</h1></div>";
}
};
</script>

Use the required keyword. This prompts the user to choose a value, when the submit button is pressed without choosing any option. And always prefer to use
<input type="submit" value="submit"> over <button>Submit Answer</button>
while handling forms. Use the onclick() event handler to call your Javascript code.
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting" required> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<input type="submit" value="submit" onclick="validate()">
</form>
And the javascript part is as follows.
<script type="text/javascript">
function validate() {
var a= document.getElementByName("choice");
for (var i = 0, i < a.length; i++) {
if (a[i].checked) {
if( a[i].value == "scripting" )
alert("your answer is correct");
else
alert("your answer is not correct");
break;
} } }
</script>

Here condition is showing in alert pop up box. but I want to show it in a html tag.
But after clicking submit button, innerHTML content showing a millisecond and then automatic remove the content. How selection will stay in innerHTML
document.getElementById("answer").innerHTML;
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
document.getElementById("answer").innerHTML = "please select choice answer";
} else if ( val == "Scripting" ) {
document.getElementById("answer").innerHTML = "Answer is correct !"
} else {
document.getElementById("answer").innerHTML = "Answer is wrong"
}
};

You can add a function and event onClick so that whenever someone clicks on option submit button will appear.

Related

Show text on a radio button selection

I have created a radio button which says "no" and "yes". By default, nothing is selected.
So what I'm looking to do here is, if someone select no, nothing happens, but if someone select "Yes" It should print a text below saying hello world.
Can someone help?
<input type="radio" value="no-charge">
No
<input type="radio" value="charge">
Yes
You need to set up event listeners for clicks on the radio buttons. When either is clicked, you need to check the value of the checked button. When it's "yes", set your message to "hello world", and blank when it's "no":
var radioY = document.getElementById("radioY");
var msg = document.getElementById("msg");
var radioQuery = document.getElementsByName("query");
function start() {
radioQuery[0].addEventListener("click", checkClicked);
radioQuery[1].addEventListener("click", checkClicked);
}
//
function checkClicked() {
for (var x = 0; x < radioQuery.length; x++) {
if (radioQuery[x].checked && radioQuery[x].value == "yes") {
msg.innerHTML = "Hello World";
return;
} else {
msg.innerHTML = "";
}
}
}
//
window.load = start();
<input name="query" value="no" type="radio"> No
<input name="query" value="yes" id="radioY" type="radio"> Yes
<div id="msg"></div>
Here's a jQuery solution you might prefer:
$(document).ready(function() {
$("#radioY").click(function() {
$("#msg").text("Hello World!");
});
$("#radioN").click(function() {
$("#msg").text("");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='radio' id='radioN' name='query' value='no' /> No
<input type='radio' id='radioY' name='query' value='yes' /> Yes
<div id="msg"></div>
Just add an event listener for click to the related element:
Javascript solution:
document.querySelector('input[value="charge"]').addEventListener("click", function()
{
document.getElementById("someId").innerHTML += "HELLO WORLD!<br>";
});
<input type="radio" name="myRadio" value="no-charge">
No
<input type="radio" name="myRadio" value="charge">
Yes
<p id="someId"></p>
JQuery solution:
$('input[value="charge"]').click(function()
{
$("#someId").html($("#someId").html() + "HELLO WORLD!<br>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myRadio" value="no-charge">
No
<input type="radio" name="myRadio" value="charge">
Yes
<p id="someId"></p>
Add an event listener like so:
document.getElementById("yes").addEventListener("click", () => console.log("Hello world!"));
<form>
<input type="radio" value="no-charge"> No
<input type="radio" value="charge" id="yes"> Yes
</form>
1.Way
let radio_1 = document.getElementById("radio_1")
radio_1.addEventListener("click",function(){
alert("hello world")
})
<input type="radio" value="no-charge" id="radio_1">
<input type="radio" value="charge" id="radio_2">
2.Way
function myAlert(){
alert("hello world")
}
<input type="radio" value="no-charge" onclick=myAlert()>
<input type="radio" value="charge" id="radio_2">
3.Way
$("#radio_1").click(function(){
alert("hello world")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="no-charge" id=radio_1>
<input type="radio" value="charge" id="radio_2">
function onChange(event) {
var x = document.getElementById("hello-world");
console.log(event.target.value);
if(event.target.value === "yes"){
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<input type="radio" name="group" value="no" onchange="onChange(event);">
No
<input type="radio" name="group" value="yes" onchange="onChange(event);">
Yes
<div id="hello-world" style="display:none">Hello World</div>
<input name="query" value="yes" id="radioY" type="checkbox"> Yes
<div id="msg"></div>
<script>
var radioY = document.getElementById("radioY");
var msg = document.getElementById("msg");
var radioQuery = document.getElementsByName("query");
function start() {
radioQuery[0].addEventListener("click", checkClicked);
radioQuery[1].addEventListener("click", checkClicked);
}
//
function checkClicked() {
for (var x = 0; x < radioQuery.length; x++) {
if (radioQuery[x].checked && radioQuery[x].value == "yes") {
msg.innerHTML = "Hello World";
return;
} else {
msg.innerHTML = "";
}
}
}
//
window.load = start();
</script>

form JavaScript function checkAnswer not loading pages

I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />

Having problems understanding checked radio buttons

I'm trying to validate my form through JavaScript and instead of manually checking each radio button I decided to loop through a group of radio buttons and check to see if they were checked or not.
I'm simply trying to see if a group of radio buttons is checked or not. But the problem I'm facing is. It's returning both true and false when I check either of them. If I don't check either, they both return false but if I check one, it returns true and false.
Here is my code:
function validateForm(){
let firstliGroup = document.getElementsByName("yesnocheck");
for(i=0; i<firstliGroup.length; i++){
//console.log(firstliGroup[i].checked);
if(firstliGroup[i].checked == true){
console.log('success');
return true;
}
else {
console.log('failed');
return false;
}
}
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<input type="submit" value="Send">
</form>
Try this:
function getRadioValue(name) {
let elements = document.getElementsByName(name);
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
return null;
}
function validateForm() {
var yesnocheck = getRadioValue("yesnocheck");
console.log(yesnocheck);
return false;
}
If nothing is checked, then getRadioValue function will return null.
If any option was checked, it will return it's value.
Try using document.forms[0].yesnocheck.
function validateForm()
{
return (document.forms[0].yesnocheck.value.length > 0 &&
document.forms[0].yesnoremote.value.length > 0 &&
document.forms[0].yesnocable.value.length > 0 &&
document.forms[0].condition.value.length > 0);
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<label for="gateremote">Gate remote batteries checked?:</label>
<input type="radio" name="yesnoremote" value="Yes"><span>Yes</span>
<input type="radio" name="yesnoremote" value="No"><span>No</span>
<label for="internetcabletv">Internet and Cable TV checked?:</label>
<input type="radio" name="yesnocable" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocable" value="No"><span>No</span>
<label for="unitcondition">Unit Condition?:</label>
<input type="radio" name="condition" value="clean"><span>Clean</span>
<input type="radio" name="condition" value="light"><span>Light</span>
<input type="radio" name="condition" value="heavy"><span>Heavy</span>
<input type="radio" name="condition" value="superheavy"><span>SuperHeavy</span>
<input type="submit" value="Send">
</form>

Making javascript check what radio form has been selected

I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...

Validation for dynamic radio button,checkbox and text area

I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>

Categories

Resources