I'm designing a online car shop as part of a small exercise. Everything going smoothly except for the total price. I want the selections to add on to the running total, depending on what radio button and check box I select, rather than each time a selection is made, the value of that selection accumulating on to my total. I hope I made explained that properly, I'd appreciate any help anyone can give!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Configure Your GT Sports Car</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<header>
<h1>Configure your GT Super Sportscar</h1>
</header>
</div></div></div>
<form name="SportsCar" id="SportsCar">
<p>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<h3>Configuration</h3>
<input type="radio" name="format" id = "Manual" value="27790.00">
<label for = "Manual">GT Manual - €27,790.00</label>
<br>
<input type="radio" name="format" id = "Automatic" value="28590.00">
<label for = "Automatic">GT Automatic - €28,590.00</label>
<br>
<input type="radio" name="format" id = "Smanual" value="32455.00">
<label for = "Smanual">GT-S Manual - €32,455.00</label>
<br>
<input type="radio" name="format" id = "Sautomatic" value="33155.00">
<label for = "Sautomatic">GT-S Automatic - €33,155.00</label>
<br>
</div>
<div class="col-md-6">
<h3>Car Colours</h3>
<label for = "colour" >Please select a colour</label>
<select name="colour" id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="silver">Silver</option>
<option value="white">White</option>
</select>
<img id="carImage" img src="images/black.jpg" alt="target_blank">
</div></div></div></div>
<div class="row">
<div class="col-md-12">
<h3>Factory Options</h3>
<input type="radio" name="fOptions" id="combo1" value="1235.00">
<label for="combo1">Option Combo 1 - €1,235.00</label>
<br>
(Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="combo2" value="3354.00">
<label for="combo2">Option Combo 2 - €3,354.00</label>
<br>
(Rear spoiler & Fog Lamps, Key-less Entry, Power Tilt & Slide Moonroof, Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="noExtras" value="0.00">
<label for="noExtras">No Extras - €0</label>
</div></div>
<br>
<div class="row">
<div class="col-md-12">
<h3>Dealer Options</h3>
<input type="checkbox" name="dealer" id="autochanger" value="550.00">
<label for = "auto-changer">CD Auto-Changer - €550.00</label>
<br>
<input type="checkbox" name="dealer" id="security" value="399.00">
<label for = "security">VIP Security System - €399.00</label>
<br>
<input type="checkbox" name="dealer" id="mirror" value="295.00">
<label for = "mirror">Auto Dimming Mirror - €295.00</label>
<br>
</div></div>
<div class="row">
<div class="col-md-12">
<br>
<label for="total" class="control-label col-md-2">Total Cost</label>
<input type="text" name="total" id="total" maxlength="3" readonly>
</div></div>
</p>
</form>
</div>
</body>
<script type="text/javascript">
var source = new Array();
window.addEventListener("load", preLoad, false);
function preLoad(){
source[0]="images/black.jpg";
source[1]="images/blue.jpg";
source[2]="images/red.jpg";
source[3]="images/silver.jpg";
source[4]="images/white.jpg";
}
carColour = document.getElementById("colour");
function handleColour(){
if(carColour.selectedIndex==0)
{
theImage.src=source[0];
}
else if(carColour.selectedIndex==1)
{
theImage.src=source[1];
}
else if(carColour.selectedIndex==2)
{
theImage.src=source[2];
}
else if(carColour.selectedIndex==3)
{
theImage.src=source[3];
}
else if(carColour.selectedIndex==4)
{
theImage.src=source[4];
}
}
theImage=document.getElementById("carImage");
carColour.addEventListener("click", handleColour, false);
</script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/calculate.js"></script>
</html>
Javascript
function formatCurrency(num) {
num = num.toString().replace(/\€|\,/g,'');
if(isNaN(num))
{num = "0";}
sign = (num == (num = Math.abs(num)));
num = num.toFixed(2);
elements= num.split(".");
num = elements[0];
cents = elements[1];
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
{num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*0+3));}
return (((sign)?'':'-') + '€' + num + '.' + cents)
}
window.addEventListener("load", handleLoad, false);
function handleLoad(){
runningTotal=parseInt(document.getElementById("Manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
cars = document.getElementById("Manual");
cars.addEventListener("click", handleConfig, false);
function handleConfig(){
if(manual.checked){
runningTotal = parseInt(document.getElementById("manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Automatic");
cars.addEventListener("click", handleConfigOne, false);
function handleConfigOne(){
if(Automatic.checked){
runningTotal = parseInt(document.getElementById("Automatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Smanual");
cars.addEventListener("click", handleConfigTwo, false);
function handleConfigTwo(){
if(Smanual.checked){
runningTotal = parseInt(document.getElementById("Smanual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Sautomatic");
cars.addEventListener("click", handleConfigThree, false);
function handleConfigThree(){
if(Sautomatic.checked){
runningTotal = parseInt(document.getElementById("Sautomatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var option = document.getElementById("combo1");
option.addEventListener("click", handleClick, false);
function handleClick(){
if(combo1.checked)
{
list=parseInt(document.getElementById("combo1").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var factory = document.getElementById("combo2");
factory.addEventListener("click", handleExtrasTwo, false);
function handleExtrasTwo(){
if(combo2.checked)
{
list=parseInt(document.getElementById("combo2").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var extras = document.getElementById("noExtras");
extras.addEventListener("click", handleNoExtras, false);
function handleNoExtras(){
if(noExtras.checked)
{
var noList=parseInt(document.getElementById("noExtras").value);
runningTotal += noList;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptions = document.getElementById("autochanger");
dealerOptions.addEventListener("click", handleOptions,false);
function handleOptions(){
if(autochanger.checked)
{
autoChange=parseInt(document.getElementById("autochanger").value);
runningTotal +=autoChange;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOption = document.getElementById("security");
dealerOption.addEventListener("click", handleOptionsTwo,false);
function handleOptionsTwo(){
if(security.checked)
{
secure=parseInt(document.getElementById("security").value);
runningTotal+=secure;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptionThree = document.getElementById("mirror");
dealerOptionThree.addEventListener("click", handleOptionThree,false);
function handleOptionThree(){
if(mirror.checked)
{
mirror=parseInt(document.getElementById("mirror").value);
runningTotal += mirror;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
As you already have jquery included in your page, you should use it. It makes your life so much simpler. Using your code as a base, I've created a simple method to sum the values of the selected elements (radio or checkbox), and display it on the total textbox.
Then you will not have to put all those click events.
Check it out: (see the running example on this fiddle: http://jsfiddle.net/b3p4r/)
$("input").change(function() {
var total = 0;
$("input").each(function() {
if($(this).is(":checked"))
total += parseFloat($(this).val());
});
$("#total").val(formatCurrency(total));
});
Related
I used to have radio buttons, but I changed the script to use bootstrap checkboxes. But it is not changing the state when using bootstrap switches.
This is snippet of my code:
<div class="form-group">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_yes" value="1" checked> Yes </label>
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_no" value="0"> No </label>
</div>
</div>
<script>
function action(){}
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_no").attr('checked', false);
$("#upd_yes").attr('checked', true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr('checked', false);
$("#upd_no").attr('checked', true);
$('#upd_no').parent().addClass('checked');
}
}
</script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>
<script>
function action(){
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_yes").attr("checked",true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr("checked",false);
$('#upd_yes').parent().removeClass('checked');
}
}
</script>
How can I fix this?
Am able to find 2 issues(actually not issues) as below
is_active is not declared so you cannot check it with if statement
Most importantly your action() function not at all initiated.
So i added below code and updated the snippet.
var is_active = 0;
action();
var is_active = 0;
action();
function action() {
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if (is_active == "1") {
$("#upd_yes").attr("checked", true);
$('#upd_yes').parent().addClass('checked');
} else {
$("#upd_yes").attr("checked", false);
$('#upd_yes').parent().removeClass('checked');
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>
presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined
I try to add new "items" to a given <select> using jQuery.
If one of the both possibiities (Countries) is checked, the "select-Box" below should change the list <options>.
This is my code:
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
This code won`t run. Why?
I believe what you want is change option for combobox depending on the selected radio button. What you need to do is to clear the combobox options first before adding new options.
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
} else if(val == "ger") {
for (var i = 1; i < 5; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
}
});
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<div id="country">
<h2>Land</h2>
<form id="selectPowerCost" name="selectPowerCost">
<fieldset>
<div class="col col-md-12" id="selectCountry">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label> <input class="left-20" id="radio-1" name="radio-1" type="radio" value="aut">
</div><!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label> <input class="left-20" id="radio-2" name="radio-1" type="radio" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select class="selectpicker" id="selectCosts" name="selectCosts" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
</body>
</html>
You only check if the country Austria is checked and not if Germany is checked.
Also i would add $("#selectCosts").empty(); before the loop to empty the items inside the list.
EDIT
You could also replace this part:
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
With this suggestion made by #Taufik Nur Rahmanda:
$('#selectCosts').append('<option value="'+i+'">Option '+i+'</option>');
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut" || $(this).val() == "ger") {
$("#selectCosts").empty();
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
Hey Guys/Girls/Developer!
Thx a lot for your support.
I solved my Problem. All suggestions are working fine.
I had included a "bootstrap-select.min.js" which made some conflicts and result in problems. As I excluded this .js-File everything works fine.
Thank you very much!
Here is the code I am using (only JS):
function init() {
$("input:radio[name=radio-1]").change(function() {
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 16; i < 22; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
} else if(val == "ger") {
for (var i = 26; i < 33; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
}
});
}
document.addEventListener('DOMContentLoaded', init);
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/
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