Javascript Quiz with 4 questions. Radiobuttons + continue button - javascript

I try to make quiz with for example 4 questions (more then one). There is 4 radiobuttons for each question and one continue button (input type="submit"). I want that when you click on continue button you will be redirected to some page (success.html) but only when all question were answered correctly. When you make some mistake in questions and click continue button it will reload quiz page.
I have tried to do this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<h3>1. otazka: otazocka</h3>
<input type="radio" name="otazka1" value="n" onClick="toggle(this)" /> Yes
<input type="radio" name="otazka1" value="n" onClick="toggle(this)" /> No
<input type="radio" name="otazka1e" value="y" onClick="toggle(this)" /> spravna
<input type="radio" name="otazka1" value="n" onClick="toggle(this)" /> asda
<br />
<input type="submit" id="continue" value="Continue" onClick=""/>
<script>
var continue_button = document.getElementById('continue');
function toggle(switchElement) {
if (switchElement.value == 'y')
continue_button.setAttribute("onClick", "window.location.href='http://www.google.sk'");
else
continue_button.setAttribute("onClick", "window.location.href='http://www.facebook.com'");
}
</script>
</body>
</html>
But it works only on one question.
I will be glad for some help.
Thanks.
Thanks for answer. But when I choose radiobutton and click on continue it didnt redirect me to any page. So I try this
<label><input type="radio" name="otazka1" value="n" /> false</label>
<label><input type="radio" name="otazka1" value="n" /> false</label>
<label><input type="radio" name="otazka1" value="y" /> true</label>
<label><input type="radio" name="otazka1" value="n" /> false</label>
<input type="submit" id="continue" value="Continue" />
<script>
var continue_button = document.getElementById('continue');
continue_button.onclick = function(event) {
var everything_OK = true;
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (inputs[i].type != "radio")
continue;
var should_be = inputs[i].value == "y";
if (inputs[i].checked != should_be) {
everything_OK = false;
break;
}
}
if (everything_OK) {
// this is not a good success-page
continue_button.setAttribute("onClick", "window.location.href='succes.html'");
} else {
continue_button.setAttribute("onClick", "window.location.href='pop.html'");
}
};
</script>
but now I must click to continue button twice. Can you help me?

You will need to loop through all your questions and look whether they are checked correctly when the Continue-button is pressed, instead of changing the full validation state of the form when only one answer was selected. Try this:
<label><input type="radio" name="otazka1" value="n" /> Yes</label>
<label><input type="radio" name="otazka1" value="n" /> No</label>
<label><input type="radio" name="otazka1" value="y" /> spravna</label>
<label><input type="radio" name="otazka1" value="n" /> asda</label>
...
<input type="submit" id="continue" value="Continue" />
<script>
var continue_button = document.getElementById('continue');
continue_button.onclick = function(event) {
var everything_OK = true;
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (inputs[i].type != "radio")
continue;
var should_be = inputs[i].value == "y";
if (inputs[i].checked != should_be) {
everything_OK = false;
break;
}
}
if (everything_OK) {
// this is not a good success-page
window.location.href = "http://www.facebook.com");
} else {
window.location.href = "http://www.google.sk";
}
};
</script>

Related

Run function if one radio input has been checked out of a group

I saw a similar question answered before, but they were too complicated for me to understand, i want a very easy way to do it, if thats possible.
So i have 6 radio inputs. I want a function to run when one of them (whichever) is checked.
html:
<input type="radio" id="AR" name="gun"> Assault Rifles <br>
<input type="radio" id="SMG" name="gun"> Submachine Guns <br>
<input type="radio" id="SG" name="gun"> Shotguns <br>
<input type="radio" id="LMG" name="gun"> Light Machine Guns <br>
<input type="radio" id="MR" name="gun"> Marksman Rifles <br>
<input type="radio" id="SR" name="gun"> Sniper Rifles <br> <br>
script:
var alleRadio = document.querySelectorAll("input");
if (alleRadio.checked === true) {}
(The if is inside a function that is started by a click)
As you might imagine this doesn't work, so what do I do?
I need super simple answers/solutions, as I am not the best in this, thank you :D
One way you could go about this is to iterate through all radio buttons when the div element is clicked and see if any of them is checked.
Here's an example:
var div = document.querySelector("div");
div.addEventListener("click", function() {
// select all input elements with type of `radio` from the page
var radioButtons = document.querySelectorAll('input[type="radio"]');
var checkedRadioButton = null;
// iterate through all radio buttons that have been found
for (var i = 0; i < radioButtons.length; i++) {
// save a reference to each individual radio button
var radioBtn = radioButtons[i];
// if a checked radio button hasn't been found yet and
// the current radio button is checked, mark it as such
// since we only care about just ANY checked button
if (!checkedRadioButton && radioBtn.checked) {
checkedRadioButton = radioBtn;
}
}
// check if `checkedRadioButton` is not `null`
if (checkedRadioButton) {
// do whatever you need here, e.g. call a function
myFunction(checkedRadioButton);
}
if (!checkedRadioButton) {
console.log('select a random radio button and click again!');
}
})
function myFunction(radioBtn) {
// do whatever you need to do with that information here
console.log(radioBtn);
console.log('radioBtn.checked', radioBtn.checked)
}
div {
border: 1px solid red;
}
<div>Clicking on this DIV will trigger a `click` event!</div>
<input type="radio" id="AR" name="gun" /> Assault Rifles <br />
<input type="radio" id="SMG" name="gun" /> Submachine Guns <br />
<input type="radio" id="SG" name="gun" /> Shotguns <br />
<input type="radio" id="LMG" name="gun" /> Light Machine Guns <br />
<input type="radio" id="MR" name="gun" /> Marksman Rifles <br />
<input type="radio" id="SR" name="gun" /> Sniper Rifles <br />
Here a sample
Hope it's help you.
app.js :
const inputs = document.querySelectorAll('.radio');
inputs.forEach(input => input.addEventListener('change', (evt) => {
if(evt.target.checked) {
// Launch your function
console.log('check');
}
}));
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="radio" id="AR" name="gun" class="radio"> Assault Rifles <br>
<input type="radio" id="SMG" name="gun" class="radio"> Submachine Guns <br>
<input type="radio" id="SG" name="gun" class="radio"> Shotguns <br>
<input type="radio" id="LMG" name="gun" class="radio"> Light Machine Guns <br>
<input type="radio" id="MR" name="gun" class="radio"> Marksman Rifles <br>
<input type="radio" id="SR" name="gun" class="radio"> Sniper Rifles <br> <br>
<script src="app.js"></script>
</body>
</html>
The reason your attempt doesn't work is because querySelectorAll returns a non-live NodeList.
var alleRadio = document.querySelectorAll("input");
The returned NodeList doesn't have the property checked. Instead you should check if one of the elements in the list is checked.
You can convert any iterable object to an array using Array.from(). You can then use Array.prototype.some() to check if at least one of the elements is checked.
const oneOrMoreChecked = Array.from(alleRadio).some(input => input.checked);
// ^ true or false
Make a var of each radio input with document.querySelector("#ID")
Example:
HTML:
<input type="radio" id="AR" name="gun"> Assault Rifles
script:
var AR = document.querySelector("#AR")
if (AR.checked || SMG.checked || SG.checked || LMG.checked || MR.checked || SR.checked)

Getting value from radio button with Javascript

I am trying to check if the radio button is checked or not, and also I am trying to get the value but I do not know why it does not work. I saw a lot of post, video on internet and also some on this site, but nothing. So helpless I am posting this on the site.
This is my HTML file
function getValue(){
var checkAge = false;
for(var i=0; i<4; i++){
if(document.getElementById("age"+i).checked){
checkAge = true;
}
}
}
function loadFunctions() {
getValue();
}
window.onload = loadFunctions;
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form id="form">
<section id="age_question">
<h2>How old are you?</h2>
<label for="age-one">1-25</label>
<input type="radio" name="ageRange" id="age1" value="0"/>
<label for="age-two">26-40</label>
<input type="radio" name="ageRange" id="age2" value="5" />
<label for="age-three">41-60</label>
<input type="radio" name="ageRange" id="age3" value="8" />
<label for="age-four">60+</label>
<input type="radio" name="ageRange" id="age4" value="10" />
</section>
<section id="bmi">
<h2>What is your BMI?</h2>
<label for="bmi-level"><span>0-25</span></label>
<input type="radio" name="bmi_range" id="" value="0"/>
<label for="bmi-level"><span>26-30</span></label>
<input type="radio" name="bmi_range" id="" value="0" />
<label for="bmi-level"><span>31-35</span></label>
<input type="radio" name="bmi_range" id="" value="9" />
<label for="bmi-level"><span>35+</span></label>
<input type="radio" name="bmi_range" id="" value="10" />
</section>
<section id="family_history">
<h2>Does anybody in your family have Diabetes?</h2>
<label for="history"><span>No</span></label>
<input type="radio" name="f_history" id="history" value="0"/>
<label for="history"><span>Grandparent</span></label>
<input type="radio" name="f_history" id="history" value="7" />
<label for="history"><span>Sibling</span></label>
<input type="radio" name="f_history" id="history" value="15" />
<label for="history"><span>Parent</span></label>
<input type="radio" name="f_history" id="history" value="15" />
</section>
<section id="diet">
<h2>How would you describe your diet?</h2>
<label for="diet"><span>Low sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0"/>
<label for="diet"><span>Normal sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0" />
<label for="diet"><span>Quite high sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="7" />
<label for="diet"><span>High sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="10" />
</section>
<button onclick="getValue()">Get You BMI</button>
<p id="message"></p>
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The first thing I'll suggest you do is to clear your browser cache, or launch the dev tools using F12 and check "Disable cache" on the "Network" tab.
Edit: Changed the button type, and made checkAge global.
Okay, the button does submit the form, making all changes to the variable lost after reload. To fix that, change the button type to just button, as:
<button type="button" onclick="getValue()">Get You BMI</button>
That way, it won't reload everytime you press the button. Another thing to do is make the checkAge variable global. that way is defined as false by default.
The "age"+i thing you did was starting the iteration with i=0, therefore giving the elementId as age0. This was making the element null.
To fix that, you can change the for-loop to for(var i=1; i<=4; i++) or using the same loop you've defined, but adding i by 1 before using it.
And the code would be like so:
var checkAge = false;
function getValue(){
for(var i=0; i<4; i++){
var index = i + 1
var element = document.getElementById("age"+index)
if(element.checked){
checkAge = true;
alert("The value is"+element.value)
}
}
}
Thanks.
Make the starting index be 1 instead of 0, since your ID selectors start from 1:
function getValue() {
var checkAge = false
for (var i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked) {
checkAge = true
}
}
console.log(checkAge)
return checkAge
}
JSFiddle Demo: https://jsfiddle.net/a3fzd2kv/2/
You don't need to check the checked value of each of the radio buttons.
Here is a simpler solution:
var form = document.getElementById('form');
var ageRange = form.ageRange.value;
The value will equal to an empty string ('') when nothing is checked. Therefore, the logic for checkAge could be simplified to:
var checkAge = ageRange !== '';
your for loop is looping through i from 0 - 3, so your document.getElementById("age"+i) will look for id="age0", "age1", "age2, "age3".
Change your 'for' loop to for(var i=1; i<5; i++)

How do you change the appearance of a button in javascript?

I'm very new to web development, so bear with me. I know how to do this when the submit button is created in the HTML page, with the help of CSS. But can you apply CSS to the javascript block? The reason I want to declare the Submit button in javascript is because eventually I want the submit button to send the choice into an SQL database, and I figure it would be much easier to do that in javascript as opposed to HTML. Please tell me if I'm completely on the wrong track.
function myFunction() {
var x = document.getElementById("myRadio");
x.checked = true;
}
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>webpage</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
Radio Button:
<input type="radio" id="myRadio">
<input type="radio" id="myRadio2">
<input type="radio" id="myRadio3">
<button onclick="myFunction()">Submit</button>
</body>
</html>
Here's the basic idea of an HTML form, which will post the values of your selected radio buttons. You can review the POST by looking at a dev tool like Firebug.
<body>
<form method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input type="submit" value="Submit">
</form>
</body>
If you want to generate the radio buttons in JavaScript/JQuery, here's a general pattern:
JSFiddle
JQuery:
//see what value is selected
$('#myForm').on('change', function() {
var selectedRadio =$('input[name="myRadio"]:checked', '#myForm').val()
console.log(selectedRadio);
});
//add more radios
$('#addRadio').on('click', function() {
var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
$('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
}
});
HTML:
<form id="myForm" method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input type="submit" value="Submit">
</form>
<input type="button" id="addRadio" value="Add Radio">
UPDATED
(JSFiddle link remains the same as above)
HTML
<form id="myForm" method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input id="myButton" type="button" value="Submit">
JQuery
//see what value is selected
$('#myForm').on('change', function() {
var selectedRadio =$('input[name="myRadio"]:checked', '#myForm').val()
console.log(selectedRadio);
});
//add more radios
$('#addRadio').on('click', function() {
var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
$('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
}
//change button style
if($(this).hasClass("warning")) {
$(this).removeClass("warning");
$(this).addClass("error");
$(this).val("Error!");
} else {
$(this).addClass("warning");
$(this).val("Warning!");
}
});
//change the button styling
$('#myButton').on('click', function() {
$(this).addClass("validated");
//you'll need to submit the form since the button is just a button and not a submit button. i've commented it out below because this is just an example
//$('#myForm').submit();
});
CSS
.validated {
background: green;
}
.warning {
background: yellow;
}
.error {
background: red;
}

default radio button selection using javascript

Here is what i wanted to accomplish. I have 2 sets of radio buttons. Radio button at the same index position in the 2 sets should not be selected at the same time. If a user tries to select, it must show alert and the defaut radio button must be selected.
Here is my html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
[enter link description here][1]
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the JS
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
It works perfectly fine. demo
Now suppose, one of the check box is not selected , say in the second set. If the user selects first radio button from second set, which is already selected in the first, an alert is showed. But the radio button remains selected.
Here is modified html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" onclick="return check();" />
Here is a demo.
NOTE: i can't use jquery since the code is already a part of some legacy application
To me it seems you should arrange the radio buttons in the other way:
<input type="radio" name="col1" value="A1">
<input type="radio" name="col2" value="A2">
<input type="radio" name="col3" value="A3">
<input type="radio" name="col1" value="B1">
<input type="radio" name="col2" value="B2">
<input type="radio" name="col3" value="B3">
That means the user only can select one value in each column without the obtrusive alert or javascript.
This works without jQuery:
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('nope')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Does this fit your needs?
Give value to your radios:
<input type="radio" name="A" checked="checked" value="1" />
<input type="radio" name="A" value="2" />
<br />
<input type="radio" name="B" value="1" />
<input type="radio" name="B" value="2" />
Then you can do as follows:
var radios = document.querySelectorAll('input[type="radio"]');
for(var i=0;i<radios.length;i++){
radios[i].addEventListener('click', check);
}
function check(){
var index= this.value-1;
if(this.name=='A'){
if(document.getElementsByName('B')[index].checked){
alert('already selectedin other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("A")[otherIndex];
other.checked= true;
}
}
else{
if(document.getElementsByName('A')[index].checked){
alert('already selected in other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("B")[otherIndex];
other.checked= true;
}
}
}
check this fiddle

html page direct

hello i am new at html i am designing a quiz in html. this is example with 2 questions only.when i click a submit button i want to calculate marks show it in a alert box and then go to result.htm page .but when i click submit alert box shows answer but page is not redirected forward to result.htm.
my code is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.d1
{
background-color:#FFFFCC;
}
#Submit1
{
width: 67px;
}
</style>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
var i = 0;
var a = document.getElementById("Radio1");
if (a.checked == true) {
i++;
}
var b = document.getElementById("Radio8");
if (b.checked == true) {
i++;
}
alert(i);
}
</script>
</head>
<body>
<p>
</p>
<form name="f1" method="post" action="d://result.htm">
<div class="d1">
Q1 What is your name ?
<br />
a <input id="Radio1" name="R1" type="radio" value="t" />
b <input id="Radio2" name="R1" type="radio" value="f" />
c <input id="Radio3" name="R1" type="radio" value="f" />
d <input id="Radio4" name="R1" type="radio" value="f" /></div>
<br /> <br /> <br />
<div class="d1">
Q1 What is your Id ?
<br />
1 <input id="Radio5" name="R11" type="radio" value="V1" />
2 <input id="Radio6" name="R11" type="radio" value="r1" />
3 <input id="Radio7" name="R11" type="radio" value="as1" />
4 <input id="Radio8" name="R11" type="radio" value="pop1" /></div>
<br /> <br /> <br />
<div class="d1">
<input id="Submit1" type="submit" value="submit" onClick="return(Submit1_onclick())"/><br />
<br /> <br />
</form>
</body>
</html>
As the last line of your function call
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
var i = 0;
var a = document.getElementById("Radio1");
if (a.checked == true) {
i++;
}
var b = document.getElementById("Radio8");
if (b.checked == true) {
i++;
}
alert(i);
location.href="result.htm";
}
</script>
This will redirect the page
Change your markup to this:
<input id="Submit1" type="submit" value="submit" onclick="Submit1_onclick();"/>
and add this to your javascript:
function Submit1_onclick() {
...
alert(i);
return true;
}
Returning true from an event handler will tell the browser to continue the default behavior (in this case, submit the form).
Sounds like you're trying to submit a POST between two static files in an IIS server, which you can't do. You can change the files to .aspx and it should work as expected.

Categories