I have to get the value of .qty input field but I have a problem that another jQuery function is rewriting the entered value after it gets entered.
For instance, if I enter 1, it gets rounded to 3,3360 but multiplied by 1 so I only can get the written value but I need the value that is changed after (3,3360) and the result should be 33.36 not 10.00:
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
You need to call the function myFunctionupdateqtyinput()inside the checkForCount function
function checkForCount() {
myFunctionupdateqtyinput();
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
myFunctionupdateqtyinput();
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
Related
This question already has answers here:
Convert NaN to 0 in JavaScript
(11 answers)
Closed 2 years ago.
I have a program I am working on that is supposed to be a makeshift discount calculator. I keep getting NaN when I try to make the program run without any input. I would like to add in a line of code that makes zero the default instead of Nan. I'm not sure what to do and any help would be appreciated!
"use strict";
var $ = function(id) { return document.getElementById(id); };
var calculateDiscountPercent = function(customerType, invoiceSubtotal) {
var discountPercent = 0;
if (customerType === "r") {
if (invoiceSubtotal < 100) {
discountPercent = .0;
} else if (invoiceSubtotal >= 100 && invoiceSubtotal < 250) {
discountPercent = .1;
} else if (invoiceSubtotal >= 250 && invoiceSubtotal < 500) {
discountPercent = .25;
} else if (invoiceSubtotal >= 500) {
discountPercent = .3;
}
} else if (customerType === "l") {
discountPercent = .3;
} else if (customerType === "h") {
if (invoiceSubtotal < 500) {
discountPercent = .4;
} else if (invoiceSubtotal >= 500) {
discountPercent = .5;
}
}
return discountPercent;
};
var processEntries = function() {
var discountAmount;
var invoiceTotal;
var discountPercent;
//get values from page, reset subtotal to 2 decimals
var customerType = $("type").value;
var invoiceSubtotal = parseFloat( $("subtotal").value );
$("subtotal").value = invoiceSubtotal.toFixed(2);
//call function to get discount percent
discountPercent = calculateDiscountPercent(customerType, invoiceSubtotal);
//calculate and display discount percent, amount, and new total
discountAmount = invoiceSubtotal * discountPercent;
invoiceTotal = invoiceSubtotal - discountAmount;
$("percent").value = (discountPercent * 100).toFixed(2) ;
$("discount").value = discountAmount.toFixed(2);
$("total").value = invoiceTotal.toFixed(2);
$("type").focus;
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("type").focus();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 500px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 10em;
}
input, select {
width: 12em;
margin-left: 1em;
margin-bottom: .5em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice Total Calculator</title>
<link rel="stylesheet" type="text/css" href="invoice_total.css">
<script type="text/javascript" src="invoice_total.js"></script>
</head>
<body>
<main>
<h1>Invoice Total Calculator</h1>
<p>Enter the two values that follow and click "Calculate".</p>
<label for="type">Customer Type:</label>
<select id="type">
<option value="r">Regular</option>
<option value="l">Loyalty Program</option>
<option value="h">Honored Citizen</option>
</select>
<br>
<label for="subtotal">Invoice Subtotal:</label>
<input type="text" id="subtotal" /><br>
----------------------------------------------------------------<br>
<label for="percent">Discount Percent:</label>
<input type="text" id="percent" disabled />%<br>
<label for="discount">Discount Amount:</label>
<input type="text" id="discount" disabled /><br>
<label for="total">Invoice Total:</label>
<input type="text" id="total" disabled /><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" />
</main>
</body>
</html>
Do this
var invoiceSubtotal = parseFloat( $("subtotal").value ) || 0 ;
I'm trying to create a BMR calculation embedded in my site. I have it working except for the gender portion (if male vs female, different calculations)
I understand that I need an adlistener but doesn't seem to be working. I think I am not referencing it properly.
Here's my code:
var theForm = document.forms["RMRform"];
var bmr;
function RMRcalc() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var gender = document.getElementById("gender").value;
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
var activitylevel = new Array();
activitylevel["sedentary"] = 1.2;
activitylevel["low"] = 1.3;
activitylevel["moderate"] = 1.5;
activitylevel["high"] = 1.7;
function getActivityLevel() {
var activityLevelamount = 0;
var theForm = document.forms["RMRform"];
var selectedActivity = theForm.elements["activity"];
activityLevelamount = activitylevel[selectedActivity.value];
return activityLevelamount;
}
if (i = this) {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) - 161) * getActivityLevel();
} else {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) + 5) * getActivityLevel();
}
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
RMRcalc();
document.getElementById('results').innerHTML = bmr;
})
body {
font: 15px gothic, sans-serif;
letter-spacing: 1px;
}
input {
width: 100%;
}
input[type=number] {
border: none;
border-bottom: 1px solid grey;
}
button[type=button] {
background-color: #ddcecb;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
color: #95483e;
padding: 16px 32px;
text-decoration: none;
letter-spacing: 1px;
margin: 4px 2px;
}
input[type=text]:focus {
border: 1px solid #555;
}
.form-inline label {
margin: 5px 10px 5px 0;
}
#media (max-width: 800px) {
.form-inline input {
margin: 10px 0;
}
.form-inline {
flex-direction: column;
align-items: stretch;
}
<form action="" id="RMRform">
<label for='gender' class="inlinelabel">
Female </label>
<input type="radio" id="gender" name="gender" value="fem" checked onclick="RMRcalc()" /><br>
<label for='gender' class="inlinelabel">
Male </label>
<input type="radio" id="gender" name='gender' value="masc" onclick="RMRcalc()" /> <br> Weight (kg):<br>
<input type="number" id="weight"><br><br> Height (cm):<br>
<input type="number" id="height"><br><br> Age (years):<br>
<input type="number" id="age"><br><br> Activity Level:
<select id="activity" name="activity">
<option value="sedentary">sedentary (1-2x/week)</option>
<option value="low">low (2-3x/week)</option>
<option value="moderate">moderate (3-4x/week)</option>
<option value="high">high (5x/week)</option>
</select>
</form> <br>
<button type="button" onclick="">
calculate</button>
<p>Your Daily Estimated Requirements</p>
<div id="results"></div>
With this, there's just no calculation showing.
Thanks in advance!
A closing } is missing for the #media query.
There shouldn't be a variable declaration in your if condition: if (var i=this). Remove the var.
Both of your radio input have the same id="gender". Id's should be unique. Consider using a class instead. This will cause problems when you later use the gender variable for your if male vs female calculations because of this selector:
var gender = document.getElementById("gender").value;
For rad to be defined in your loop...
var rad = document.myForm.myRadios;
...you'll need to change myRadios to gender, because that's the name of your radio inputs. You'll also need to give your form the name myForm.
<form action="" id="RMRform" name="myForm">
Perhaps you're looking for something in this region...
function calc () {
const gender = document.querySelector('input[name="gender"]:checked').value,
weight = document.getElementById('weight').value,
height = document.getElementById('height').value,
age = document.getElementById('age').value,
activity = document.getElementById('activity').value;
// calculate base metric value
let metricBase = ((10 * weight) + (6.25 * height) - (5 * age));
// calculate per gender
metricBase = (gender === 'fem') ? metricBase - 161 : metricBase + 5;
// calculate with inline activity values
const bmr = Math.round( metricBase * parseFloat(activity) );
// format caloric intake output
document.getElementById('results').innerHTML = `${bmr.toLocaleString()} calories/day`;
}
// prevents form change listener until after first calculation
let firstCalc = true;
document.getElementById('calc').addEventListener('click', () => {
if (firstCalc) document.querySelector('form').onchange = calc;
firstCalc = false;
calc();
}, false);
body {
}
body, input {
font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
font-size: 14px;
letter-spacing: 1px;
}
input[type="radio"] {
display: inline-block;
width: 1rem;
}
input[type="number"] {
border: none;
border-bottom: 1px solid #ccc;
}
.group {
padding: .5rem 0;
}
<form>
<div class="group">
<label class="radio">
<input type="radio" name="gender" value="fem" checked />
Female
</label>
<label class="radio">
<input type="radio" name='gender' value="masc" />
Male
</label>
</div>
<div class="group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" value="79" />
</div>
<div class="group">
<label for="weight">Height (cm):</label>
<input type="number" id="height" value="172" />
</div>
<div class="group">
<label for="weight">Age (years):</label>
<input type="number" id="age" value="22" />
</div>
<div class="group">
<label for="activity">Activity Level:</label>
<select id="activity">
<option value="1.2" selected>Sedentary (1-2x/week)</option>
<option value="1.3">Low (2-3x/week)</option>
<option value="1.5">Moderate (3-4x/week)</option>
<option value="1.7">High (5x/week)</option>
</select>
</div>
<button type="button" id="calc">Calculate</button>
</form>
<p id="results"></p>
Here is what i see (i am quite new to JS so i may not see everything) :
There is no opening head tag (not sure if that's a problem).
The gender radio buttons both have the same id. IDs should be unique. And because of this my guess is that this code should only give you the value for fem no ?:
html:
<input type="radio" id="gender" name="gender" value="fem" checked
onclick="RMRcalc()" />
<input type="radio" id="gender" name='gender' value="masc"
onclick="RMRcalc()" />
js:
var gender = document.getElementById("gender").value;
In your for-loops i would use let instead of var, otherwise you might get in trouble someday. Checkout this post.
for (let i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
I didn't understand this in your function RMRcalc : if (var i = this)
<pre>
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<pre>
This is loop.
I want to get input value when i click quantity up & down button each time. There are multiple elements.
How to find input value in javascript by clicking button up & down.
You can add onClick event with parents feature to detect the inputs near to the button.
$(document).on('click','.quantity-up',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)+1);
});
$(document).on('click','.quantity-down',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)-1);
});
.quantity {
padding: 10px;
}
.quantity-nav{
display: inline-block;
}
.quantity-button {
display: inline-block;
padding: 5px;
background-color: #c7c5c5;
border: 1px solid #585353;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
</div>
Thanks :-)
Actually your problem is quite easy to solve.
Try to add this script at the end of your <body>.
I suggest you to make some modifications in your html too: use <button> or <input type="button"or even <a> tags for your controls.
I added some logic about the min/max/step attributes you can set on a <input type="number"> but this is optional. It's up to you to change this.
document.addEventListener("DOMContentLoaded", function() {
const qtyWraps = document.getElementsByClassName('quantity');
for (let i = 0; i < qtyWraps.length; i++) {
const qtyWrap = qtyWraps.item(i);
const input = qtyWrap.querySelector('.form-qty');
const up = qtyWrap.querySelector('.qty-up');
const down = qtyWrap.querySelector('.qty-down');
const output = qtyWrap.querySelector('.output');
up.addEventListener('click', function(e) {
e.preventDefault();
addValue(1);
});
down.addEventListener('click', function(e) {
e.preventDefault();
addValue(-1);
});
input.addEventListener('input', function() {
output.textContent = input.value
});
const addValue = function(value) {
const current = parseInt(input.value);
const min = input.getAttribute('min') || -Infinity;
const max = input.getAttribute('max') || Infinity;
const step = input.getAttribute('step') || 1;
const newValue = Math.min(max, Math.max(min, current + value * step));
input.value = newValue;
if (newValue <= min) down.setAttribute('disabled', 'disabled');
else down.removeAttribute('disabled');
if (newValue >= max) up.setAttribute('disabled', 'disabled');
else up.removeAttribute('disabled');
input.dispatchEvent(new Event('input'));
}
addValue(0)
}
});
.quantity {
display: block;
width: 500px;
margin: auto;
text-align: center;
}
.quantity .form-qty {
display: inline-block;
}
.quantity .quantity-nav {
display: inline-block;
}
.quantity .output {
background: yellow;
width: 500px;
margin: 1em auto 0;
}
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<button class="quantity-button quantity-up qty-up">+</button>
<button class="quantity-button quantity-down qty-down">-</button>
</div>
<!-- I put it here to show the output result -->
<div class="output">1</div>
</div>
You can use localStorage to store the value of your quantity, this would make the data persistent.
Please check the below code snippet:
const down = document.querySelector('.down');
const up = document.querySelector('.up');
const input = document.querySelector('.quantity');
// store utility function
const store = {
existsIn: function(key) {
return this.getFromKey(key) !== null;
},
getFromKey: function(key) {
return window.localStorage.getItem(key);
},
add: function(key, value) {
const storeSource = window.localStorage.setItem(key, value);
}
}
const quantity = Object.create(store);
quantity.exists = function() {
return this.existsIn('quantity');
}
quantity.increase = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
storedQuantity = storedQuantity + 1;
this.add('quantity', storedQuantity);
}
quantity.decrease = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
if(storedQuantity > 0) {
storedQuantity = storedQuantity - 1;
}
this.add('quantity', storedQuantity);
}
quantity.show = function() {
return this.exists() ? this.getFromKey('quantity') : 0;
}
// event listeners for up and down buttons
up.addEventListener('click', function() {
quantity.increase();
// update input on button click
input.value = quantity.show();
})
down.addEventListener('click', function() {
quantity.decrease();
// update input on button click
input.value = quantity.show();
})
// update input on page load
input.value = quantity.show();
There you can find a working fiddle:
https://jsbin.com/tavalocoti/5/edit?html,js,console,output
The page should output and execute a temperature converter...
However,
While I'm wanting to test my program, I keep running into this a blank page type error...
can someone kind of proof read this, because I don't know what I'm missing.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var convertTemp = function(){
var f;
var c;
if($("to_Celsius").checked){
f = parseFloat($("degrees_entered").value);
if(isNaN(f)){
alert("please type in a value ");
}
else{
c = (f-32) * 5/9;
$("degrees_computed").value = c.toFixed(0);
}
}
else{
c = parseFloat($("degrees_entered").value);
if(isNaN(c)){
alert("you must enter a valid number for degrees.");
}
else{
f = c * 9/5 + 32;
$("degrees_computed").value = f.toFixed(0);
}
}
};
var toFahrenheit = function(){
$("degree_label_1").firstChild.nodeValue = "Enter C degrees:";
$("degree_label_2").firstChild.nodeValue = "Degrees F";
clearTextBoxes();
$("degrees_entered").focus();
};
var toCelsius = function(){
$("degree_label_1").firstChild.nodeValue = "Enter F degrees: ";
$("degree_label_2").firstChild.nodeValue = "Degrees C: ";
clearTextBoxes();
$("degrees_entered").focus();
};
var clearTextBoxes = function(){
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function(){
$("convert").onclick = convertTemp;
$("to_Celsius").onclick != toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
toCelcius != toCelsius ?
Is that it? A silly typo? The rest looks fine... also watch casing. In your JS you have to_Celsius... but in the html... to_celcius... bad habit for sure
Some issues I verified:
in the line if($("to_Celsius").checked){ you refer to to_Celsius id, but it should be to_celsius (lowercase);
in the lines:
$("to_Celsius").onclick = toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
Same thing. Replace both the id with to_celsius and to_fahrenheit.
in this line var toCelcius = function(){, the function is named toCelcius. Just rename it to toCelsius (with s).
Working code: https://jsfiddle.net/mrlew/p8w111ms/
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help?
Here is my jsfiddle http://jsfiddle.net/clbacon70/x6kjqbop/1/
var gc_fSandwichPrice = 5.99; // Price for each sandwich
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var divErrors;
var radSandwich;
var radSize;
var chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
window.addEventListener('load', Init);
function Init() {
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
var spanExtrasPrice = document.getElementById("spanExtrasPrice");
var btnCalculateTotal = document.getElementById("btnCalculateTotal");
divErrors = document.getElementById("divErrors");
radSandwich = document.getElementsByName('radSandwich');
radSize = document.getElementsByName('radSize');
chkExtras = document.getElementsByName('chkExtras');
spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2);
btnCalculateTotal.addEventListener('click', CalculateTotal);
} // function Init()
function CalculateTotal() {
divErrors.innerHTML = '';
if (radSandwich[0].checked) {
g_sSandwich = radSandwich[0].value;
} else if (radSandwich[1].checked) {
g_sSandwich = radSandwich[1].value;
} else if (radSandwich[2].checked) {
g_sSandwich = radSandwich[2].value;
} else if (radSandwich[3].checked) {
g_sSandwich = radSandwich[3].value;
} else {
divErrors.innerHTML = "Select a Sandwich";
return;
}
if (radSize[0].checked){
g_fTotal = radSize[0].title;
} else if (radSize[1].checked) {
g_fTotal = radSize[1].title;
} else if (radSize[2].checked) {
g_fTotal = radSize[2].title;
} else {
divErrors.innerHTML = "Please choose a size";
return;
}
if (chkExtras[0].checked) {
g_sExtras = chkExtras[0].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
if (chkExtras[1].checked) {
g_sExtras = g_sExtras + ',' + chkExtras[1].value;
g_fTotal = g_fTotal + gc_fExtrasPrice; }
if (chkExtras[2].checked) {
g_sExtras = g_sExtras +', ' + chkExtras[2].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
var textTotal = document.getElementById('textTotal');
textTotal.value = g_fTotal;
} // function CalculateTotal
function ProcessOrder() {
} // function ProcessOrder
* {
margin: 0;
padding: 0;
}
body {
background-color: #333;
}
#divWrapper {
background-color: #efe;
width: 40em;
border: solid black;
border-radius: 0 0 20px 20px;
border-width: 0 1px 1px 1px;
margin: 0 auto;
padding: 2em 1em;
}
h2 {
font-style: italic;
font-size: 1.3em;
color: #666;
margin-top: 0px;
}
input {
margin-right: 0.3em;
}
h3, p {
margin: 0.5em 0;
}
div#divErrors {
font-size: 110%;
color: white;
background: #f00;
margin-bottom: 0.5em;
}
#divPaymentInfo {
margin: 10px 0 20px 0;
padding-bottom: 10px;
border: solid black;
border-width: 1px 0;
}
#divCreditCardInfo {
font-size: .8em;
visibility: hidden;
margin-left: 1em;
display: inline;
}
#divOrder {
background: white;
min-height: 10em;
width: 25em;
border: 1px solid black;
margin: 0.5em 0;
padding: 10px;
}
<body>
<div id="divWrapper">
<form name="frmMain">
<h1 id="h1Title">Deli Form</h1>
<h2>Part 1</h2>
<h3>Sandwich</h3>
<label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br>
<label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br>
<label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br>
<label><input type="radio" name="radSandwich" value="ReelMeatĀ®">ReelMeatĀ®</label><br>
<br>
<h3>Size</h3>
<label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>
<label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>
<label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label>
<br><br>
<h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3>
<label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br>
<label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br>
<label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br>
<br><br>
Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total">
<br><br>
<div id="divErrors"></div>
<div id="divPaymentInfo">
<h2>Part 2</h2>
<strong>Customer's Name:</strong> <input type="text" id="txtName">
<br><br>
<strong>Payment:</strong>
<select id="selPayment">
<option value="Cash" selected="selected">Cash</option>
<option value="Check">Check</option>
<option value="Credit Card">Credit Card</option>
</select>
<div id="divCreditCardInfo">
Card Number: <input type="text" id="txtCreditCardNbr" size="20">
Month: <input type="text" id="txtMonth" size="2"> Year:
<select id="selYear">
<option value="" selected="selected"></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2010">2017</option>
<option value="2011">2018</option>
</select>
</div><!-- divCreditCardInfo -->
</div><!-- divPaymentInfo -->
<input type="button" id="btnProcessOrder" value="Process Order">
<div id="divOrder"></div>
<input type="reset" value="Reset">
</form>
</div> <!-- divWrapper -->
</body>
You have a typo in your javascript. You are attempting to fetch an html element with id textTotal, when the field you're interesting in is actually given the id txtTotal.
Fix that typo and it will work.
var textTotal = document.getElementById('textTotal');
Your selector is wrong. The element id of your textbox is txtTotal
so the following should work:
var textTotal = document.getElementById('txtTotal');
Here's a fixed copy of your jsFiddle: http://jsfiddle.net/dcseekcw/
What I fixed:
You were passing in $ along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated.
Put in parseFloat so values could be added together instead of being concatenated as strings.
Initialised your g_fTotal and chkExtras variables.
Put in some basic checking so that radSize doesn't cause problems when it's not selected.
You have to add brackets after 'Init'.
window.addEventListener('load', Init());
And also there was a typo in the end of CalculateTotal function.
Here is working example:
http://jsfiddle.net/x6kjqbop/3/