JavaScript multiple choice quiz . display one page at a time - javascript

I have made a JavaScript quiz and it might be an obvious fix but I've been stuck attempting to display one question at a time. I want to display the next question when I click next. However I am unable to find a way to do this. p.s I am not a JavaScript pro.
This is my current code:
<form id="form1" action=" ">
<center>
<h3><br><img src='images/bulb logo.png' width = '30'/>Did you turn off your heating in the day time?</h3></center>
<center>
<input type="radio" name="variable" value="25" /> YES</center>
<br />
<center>
<input type="radio" name="variable" value="0" /> NO</center>
<br />
<audio id="myTune">
<source src="sounds/buttonclick.mp3">
<source src="sounds/buttonclick.ogg">
</audio>
<center>
<h3> <br><img src='images/bulb logo.png' width = '30'/>Did you switch off lights when not needed?</h3></center>
<center>
<input type="radio" name="sub" value="25" /> YES</center>
<br />
<center>
<input type="radio" name="sub" value="0" /> NO</center>
<br />
<center>
<h3><br><img src='images/bulb logo.png' width = '30'/> Did you turn off your computer monitor when not in use?</h3></center>
<center>
<input type="radio" name="con" value="25" /> YES</center>
<br />
<center>
<input type="radio" name="con" value="0" /> NO</center>
<br />
<center>
<h3> <br><img src='images/bulb logo.png' width = '30'/> Have you turned off power outlets?</h3></center>
<center>
<input type="radio" name="if" value="25" /> YES</center>
<br />
<center>
<input type="radio" name="if" value="0" /> NO</center>
<br />
<center>
<input type="submit" value="Submit" id="submit" onclick="document.getElementById('myTune').play()" />
</center>
</form>
<center>
<h2> You scored : <span id="grade">__</span></h2></center>
<p id="grade2"></p>
</div>
<script>
//get form selection once submitted and calculate the score
document.getElementById("form1").onsubmit = function() {
variablevar = document.getElementsByName("variable");
for (i = 0; i < variablevar.length; i++) {
if (variablevar[i].checked) {
vscore = parseInt(variablevar[i].value);
}
}
subvar = document.getElementsByName("sub");
for (i = 0; i < subvar.length; i++) {
if (subvar[i].checked) {
sscore = parseInt(subvar[i].value);
}
}
convar = document.getElementsByName("con");
for (i = 0; i < convar.length; i++) {
if (convar[i].checked) {
cscore = parseInt(subvar[i].value);
}
}
ifvar = document.getElementsByName("if");
for (i = 0; i < ifvar.length; i++) {
if (ifvar[i].checked) {
iscore = parseInt(ifvar[i].value);
}
}
result = vscore + sscore + cscore + iscore;
document.getElementById("grade").innerHTML = result;
if (result == 0) {
result2 = "Make more efforts to save energy."
};
if (result == 25) {
result2 = "A little goes a long way, try harder"
};
if (result == 50) {
result2 = "I think you could do better. Try again.<br/><img src='images/badge_4.jpg' width = '100'/>"
};
if (result == 75) {
result2 = "Welldone. So close to being green<br/><img src='images/badge_3.jpg' width = '100'/>"
};
if (result == 100) {
result2 = "Excellent! You're a natural conserver!<br/><img src='images/badge_4.jpg' width = '100'/>"
};
document.getElementById("grade2").innerHTML = result2;
return false;
}
</script>

Related

I am building multiple checkboxes. I want to add the functionality

I am building multiple checkboxes. I want to add the functionality, where in a group one checkbox only one checkbox should checked with right or wrong value. After selecting all the groups submit button should be enables.After clicking on submit button, value of each group should (right or wrong answer) should be displayed.How should I go about doing that ?
function isChecked(checkbox, sub1) {
document.getElementById(sub1).disabled = !checkbox.checked;
}
$("input:checkbox").on('click', function() {
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
//alert("checked");
} else {
$box.prop("checked", false);
}
var bool;
$("input.checkbox").change(function() {
bool = $(".checkbox:not(:checked)").length != 6;
// enable/disable
$("#submitbutton").prop('disabled', bool).addClass('btn');
// $("#submitbutton").removeAttr("disabled", bool).addClass("btn");
//$('#submitbutton').removeClass('btn1').prop(':disabled', bool).addClass('btn');
<!-- alert('right')-->
}).change('color');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />
<input type="checkbox" class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1" />
<input type="checkbox" class="checkbox checkbox_1" id="button3" name="fooby[1][]" value="chk2" /><br>
<input type="checkbox" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />
<input type="checkbox" class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />
<input type="checkbox" class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />
<input type="checkbox" class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />
<input type="checkbox" class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>
<input type="submit" value="Submit" id="submitbutton" disabled="disabled" class="btn" />
As specified in the comments you can use RadioButton instead of Checkbox this will handle for your the checking stuffs. However, to enable the submit button you have to do some maths, by verifying if the number of the checked radio buttons is the half of the total number of the radio buttons:
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}
Finally, here is a demo:
$("input[type='radio']").on("change",function(){
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />
<input type="radio" class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1" />
<input type="radio" class="checkbox checkbox_1" id="button3" name="fooby[1][]" value="chk2" /><br>
<input type="radio" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />
<input type="radio" class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />
<input type="radio" class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />
<input type="radio" class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />
<input type="radio" class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>
<input type="submit" value="Submit" id="submitbutton" disabled="disabled" class="btn"/>
<FORM NAME=MAIN>
<SCRIPT>
HTML = [];
function PRINT(L, X) { HTML.push(L.split("#").join(X)); }
function FLUSH() { document.write(HTML.join("")); HTML = []; }
COOKIE = "ANSWERS";
function SetCookie(NAME, VALUE) { var E = new Date(); E.setFullYear(E.getFullYear() + 5); document.cookie = NAME + "=" + VALUE + ";Expires=" + E.toGMTString(); }
function GetCookie(NAME) { var i, e, s, K = document.cookie.split(";"); for (i = 0; i < K.length; i++) { for (s = 0; K[i].charCodeAt(s) < 33; s++); e = K[i].indexOf("="); if (K[i].substring(s, e) == NAME) return K[i].slice(++e); } return ""; }
BOX_COLOR = "0033CC";
TEXT_COLOR = "FFFFFF";
ROW_COLORS = "111133 333355".split(" ");
Q = "Do you speak English?|Do you have an Apple iPhone X ?|Do you write JavaScript?|Have you ever caught an alligator?|Did you eat it?|Do you like winter?|Is the earth big?|Zero equals false. Agree?|Does your laptop run on 19 volts?".split("|");
ANSWER = GetCookie(COOKIE);
if (ANSWER && ANSWER != null) ANSWER = ANSWER.split(","); else ANSWER = [];
for (i = ANSWER.length; i < Q.length; i++) ANSWER.push(0);
PRINT("<TABLE CELLSPACING=1 CELLPADDING=7 BGCOLOR=#>", BOX_COLOR);
PRINT("<TR><TD>#True<TD>#False<TD>#Questions", "<FONT COLOR=" + TEXT_COLOR + ">");
for (i = 0; i < Q.length; i++)
{
PRINT("<TR BGCOLOR=#>", ROW_COLORS[i&1]);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==1?"CHECKED":"")+" NAME=X#A TYPE=CHECKBOX onClick='K(#, 1);'>", i);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==2?"CHECKED":"")+" NAME=X#B TYPE=CHECKBOX onClick='K(#, 2);'>", i);
PRINT("<TD onClick='K(#, 0);'><FONT COLOR="+TEXT_COLOR+">"+(i+1)+". " + Q[i], i);
}
PRINT("</TABLE><P>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Get Answers ' onClick='alert(ANSWER);'>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Delete Answers ' onClick='DeleteAnswers();'>");
PRINT("<INPUT TYPE=BUTTON "+(isComplete()?"":"DISABLED")+" NAME=NEXT VALUE=' NEXT ' onClick='Next();' onMouseOver='CheckAnswers();'>");
FLUSH();
function K(N, V) // Click event handler
{
var A = 1;
if (ANSWER[N] == 1 || (ANSWER[N] == 0 && V == 2)) A = 0;
ANSWER[N] = (A) ? 1 : 2;
eval("document.MAIN.X"+N+"A.checked = A;");
eval("document.MAIN.X"+N+"B.checked = !A;");
CheckAnswers();
SaveAnswers();
}
function isComplete() { for (var i = 0; i < Q.length; i++) if (ANSWER[i] == 0) return 0; return 1; }
function AllowNext() { document.MAIN.NEXT.disabled = false; }
function CheckAnswers() { if (isComplete()) AllowNext(); }
function Next() { location.href = "http://www.msn.com"; }
function SaveAnswers() { SetCookie(COOKIE, ANSWER.join(",")); }
function DeleteAnswers()
{
for (var i = 0; i < Q.length; i++)
{
ANSWER[i] = 0;
eval("document.MAIN.X"+i+"A.checked = false;");
eval("document.MAIN.X"+i+"B.checked = false;");
}
document.MAIN.NEXT.disabled = true;
SetCookie(COOKIE, "");
}
</SCRIPT>

Browser compatibility issues Javascript

I got the following Javascript code that works properly in Mozilla Firefox but it doesn't in Google Chrome. Any ideea why it will do that?
totalBMI in Chrome even if the value is 45(checking all the last buttons will give you the value 45 which is bigger then 26 so the result should be setting the hRisk div to display:-inline instead of display:none, as the function changeCss() does.) it still consider it to be 0, cause it displays the low risk message. In Firefox, it always displays the right answer.
Javascript code :
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
}
changeCSS();
} else if (totalBMI > 16 ) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
}
changeCSS();
} else {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
changeCSS();
}
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
HTML code:
<script src="jsbmi4.js"></script>
<title>Java</title>
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"> <span class="span1"> How old are you? </span>
<input type="radio" id="age1" name="age" value="0">0-25
<input type="radio" id="age1" name="age" value="5">26-40
<input type="radio" id="age1" name="age" value="8">41-60
<input type="radio" id="age1" name="age" value="10">60+
</label>
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span>
<input type="radio" id="bmi1" name="bmi" value="0">0-25
<input type="radio" id="bmi1" name="bmi" value="0">26-30
<input type="radio" id="bmi1" name="bmi" value="9">31-35
<input type="radio" id="bmi1" name="bmi" value="10">35+
</label>
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes? </span>
<input type="radio" id="fam1" name="fam" value="0">No
<input type="radio" id="fam1" name="fam" value="7">Grandparent
<input type="radio" id="fam1" name="fam" value="15">Sibling
<input type="radio" id="fam1" name="fam" value="15">Parent
</label>
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span>
<input type="radio" id="diet1" name="diet" value="0">Low sugar
<input type="radio" id="diet1" name="diet" value="0">Normal sugar
<input type="radio" id="diet1" name="diet" value="7">Quite high sugar
<input type="radio" id="diet1" name="diet" value="10">High sugar
</label>
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()">
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
Only modification that I had to do is delete the function changeCSS() and just add what was inside in the if statement.
Thanks Fuximus Foe.
JSCode is here.
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
} else if (totalBMI > 16 ) {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
} else {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
}
You have not closed any input tags consider using <input ... /> self closing tags. You have misplaced closing </label> tags.
You shouldn't redeclare a function just to use on the next line.
Not sure, why you're binding to onclick event when you already have the answer, that makes it work only when the user hits the calculate button twice.
After fiddling around with this, removing the the changeCSS functions and just executing their code straight away fixes the problem. This is because in Chrome is grabbing the first definition of the function regardless whether the cursor reaches it or not, thus executing only the first changeCSS function on all three cases; firefox reads the correct definition.
JAVASCRIPT:
function CalculateValue() {
var totalBMI = 0+parseInt(getAgeValue('age'))
+parseInt(getBmiValue('bmi'))
+parseInt(getFamValue('fam'))
+parseInt(getDietValue('diet'));
alert(totalBMI);
if (totalBMI > 26) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'block';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
//}
//}
//changeCSS();
} else if (totalBMI > 16) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'block';
//}
//}
//changeCSS();
} else {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'block';
//}
//}
//changeCSS();
}
}
function getAgeValue() {
for (var i = 0; i < document.getElementsByName('age').length; i++) {
if (document.getElementsByName('age')[i].checked) {
return document.getElementsByName('age')[i].value;
}
}
return 0;
}
function getBmiValue() {
for (var i = 0; i < document.getElementsByName('bmi').length; i++) {
if (document.getElementsByName('bmi')[i].checked) {
return document.getElementsByName('bmi')[i].value;
}
}
return 0;
}
function getFamValue() {
for (var i = 0; i < document.getElementsByName('fam').length; i++) {
if (document.getElementsByName('fam')[i].checked) {
return document.getElementsByName('fam')[i].value;
}
}
return 0;
}
function getDietValue() {
for (var i = 0; i < document.getElementsByName('diet').length; i++) {
if (document.getElementsByName('diet')[i].checked) {
return document.getElementsByName('diet')[i].value;
}
}
return 0;
}
HTML:
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"><span class="span1"> How old are you?</span></label>
<input type="radio" id="age1" name="age" value="0"/>0-25
<input type="radio" id="age1" name="age" value="5"/>26-40
<input type="radio" id="age1" name="age" value="8"/>41-60
<input type="radio" id="age1" name="age" value="10"/>60+
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span></label>
<input type="radio" id="bmi1" name="bmi" value="0"/>0-25
<input type="radio" id="bmi1" name="bmi" value="0"/>26-30
<input type="radio" id="bmi1" name="bmi" value="9"/>31-35
<input type="radio" id="bmi1" name="bmi" value="10"/>35+
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes?</span></label>
<input type="radio" id="fam1" name="fam" value="0"/>No
<input type="radio" id="fam1" name="fam" value="7"/>Grandparent
<input type="radio" id="fam1" name="fam" value="15"/>Sibling
<input type="radio" id="fam1" name="fam" value="15"/>Parent
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span></label>
<input type="radio" id="diet1" name="diet" value="0"/>Low sugar
<input type="radio" id="diet1" name="diet" value="0"/>Normal sugar
<input type="radio" id="diet1" name="diet" value="7"/>Quite high sugar
<input type="radio" id="diet1" name="diet" value="10"/>High sugar
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()"/>
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk" style="display:none;">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
and the JSFiddle: http://jsfiddle.net/kWyx8/

Basic Calculations using Javascript for Holiday Booking System

********************************** EDIT *********************************
HERE IS LINK TO JSFIDDLE TO MAKE IT EASIER TO ANALYSE WHAT I'M TRYING TO RESOLVE
http://jsfiddle.net/Kaleidoscar/ZEd5V/
I have a college assignment to complete which requires me to calculate the price of a hotel and multiply it by the number of days plus any extras to be added to the price of the hotel.
Unfortunately, the code I've provided doesn't work and I'm not sure how I can multiply the hotel price with the holiday duration... If anyone can help me with this problem, I would gladly appreciate the help.
Here is the html code for my assignment:
HTML
Hotels
<div class ="HotelBooking">
<form id="getHotelBooking" onsubmit="return false;">
<ul>
<li><input type="radio" id="Miramar" name="selectedhotel" value="Hotel Miramar" /> Hotel Miramar</li>
<li><input type="radio" id="Jazminas" name="selectedhotel" value="Las Jazminas" /> Las Jazminas</li>
<li><input type="radio" id="Tropicana" name="selectedhotel" value="Tropicana Gardens" /> Tropicana Gardens</li>
</ul>
<input type="button" value="OK" class="buttonstyle" onclick="testHotelImages()" />
<!--INFORMATION ICONS -->
<div class="informationWrap">
<img src="images/information_italic.png" alt="info" class ="infoIcon" />
<p class="imgDescription">Please choose from the selection of Hotels provided. Only 1 hotel can be purchased per hotel booking. To the left hand-side, a hotel description will appear. Only press the OK command once you have confirmed your hotel stay.</p>
</div>
<img id="PricePlaceHolder" src="images/PricePlaceHolder.jpg" alt="Image gallery" height="150" width="150" />
<div class ="Images">
<img id="Hotelplaceholder" src="images/Hotelplaceholder.jpg" alt="Image gallery" height="300" width="615" />
</div>
</form>
</div>
Options
<div class ="HotelBooking">
<form id="getOptionsBooking" onsubmit="return false;">
<ul>
<li><input type="checkbox" id="local" name="check" value="LocalTourOption" /> Tours to Local Interests</li>
<li><input type="checkbox" id="flyDrive" name="check" value="FlyDriveOption" /> Fly-Drive (have a rental car waiting at the airport)</li>
<li><input type="checkbox" id="balcony" name="check" value="BalconyOption" /> Balcony</li>
</ul>
<p><input type="button" class="buttonstyle" value="OK" onclick="ExtraInterest()" /></p>
Duration
<form id="FormNights" action="#">
<p><label for="Nights">Nights:</label>;
<input type="text" size="10" id="Nights" /> </p>
Your Party
<form id="Party" action="#">
<p><label for="Adults">Adults:</label>
<input type="text" size="2" id="AdultsParty" /> </p>
<p><input type="button" class="buttonstyle" value="OK" onclick="PartyDetails()" /></p>
</form>
<h3>Your Holiday Summary</h3>
<div id="TotalCost"> </div>
JAVASCRIPT
var hotel_prices = new Array();
hotel_prices["Hotel Miramar"] = 50;
hotel_prices["Las Jazminas"] = 75;
hotel_prices["Tropicana Gardens"] = 100;
function getHotelPrice() {
var HotelSizePrice = 0;
var theForm = document.forms["getHotelBooking"];
var selectedHotel = theForm.elements["selectedhotel"];
for (var i = 0; i < selectedHotel.length; i++) {
if (selectedHotel[i].checked) {
HotelSizePrice = hotel_prices[selectedHotel[i].value];
break;
}
}
return HotelSizePrice;
function LocalExtra() {
var LocalPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeLocal = theForm.elements["local"];
if (includeLocal.checked == true) {
LocalPrice = 60;
}
return LocalPrice;
}
function FlyDriveExtra() {
var FlyDrivePrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeFlyDrive = theForm.elements["flyDrive"];
if (includeFlyDrive.checked == true) {
FlyDrivePrice = 45;
}
return FlyDrivePrice;
}
function BalconyExtra() {
var BalconyPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeBalcony = theForm.elements["balcony"];
if (includeBalcony.checked == true) {
BalconyPrice = 30;
}
return BalconyPrice;
}
function getNights() {
var theForm = document.forms["FormNights"];
var quantity = theForm.elements["Nights"];
var duration = 0;
if (quantity.value != "") {
duration = parseInt(quantity.value);
}
return duration;
}
function getAdults() {
var theForm = document.forms["Party"];
var quantity = theForm.elements["AdultsParty"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
function getTotal() {
var HotelPrice = getHotelPrice() + LocalExtra() + FlyDriveExtra() + BalconyExtra() + getNights() + getAdults();
document.getElementById('TotalCost').innerHTML =
"Total Price For Hotel £" + HotelPrice;
}
}

how to output value from radio button

i am trying to output value of radio with innerHTML
But i do not succeed in this. What is going wrong?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
It's getElementsByName (plural).
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
jsFiddle example
And you probably want the value (userInputgender[i].value;) returned to your div.
You could use jquery, it's much better. Look at this example:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
http://jsfiddle.net/LZWau/1/
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
http://jsfiddle.net/ayy28/4/
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});

Get Radio Value to Carry over pages with Javascript

I am trying to build a very simple dot chasing game as a homework assignment, and I cannot figure out how to carry over the difficulty selection from the index page to the actual game page.
Index Page
<form id="difficulty" name="difficulty" action="game.html">
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onClick="setDifficulty()"/>
</form>
Game Page
<html>
<head>
<title>DotSmasher</title>
<link rel="stylesheet" href="dotSmasher.css" type="text/css">
<script src="dotSmasher.js" type="text/javascript"></script>
</head>
<body onLoad="setGameAreaBounds(); startGameTimer()" onResize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0</div>
<div id="pageTitle">DotSmasher</div>
<div id="start">
<button id="startButton" onClick="start()">Start</button>
</div>
<div id="stop">
<button id="stopButton" onClick="pause()">Stop</button>
</div>
<div id="gameArea">
<button id="dot" onClick="detectHit()"></button>
</div>
</body>
</html>
JavaScript Code
Variables count, timer, and difficulty are instantiated at the beginning of the page
var score = 0;
var aWidth;
var aHeight;
var timer;
var count = 30;
var counter = setInterval(startGameTimer, 1000);
var difficulty;
function startGameTimer(){
count -= 1;
if (count <= 0){
clearInterval(counter);
clearTimeout(timer);
alert("Game has ended, Thank you for playing on " + difficulty + "!");
return;
}
}
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
}
}
}
For some reason i am getting an undefined error and cannot figure out what it could be.
You need to put your script at the top in your page and in head tag, try this:
<script>
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
alert(difficulty);
}
}
}
</script>
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onclick="setDifficulty();"/>
Here is DEMO

Categories

Resources