Using Radio Button Values in Javascript - javascript

Following on from my previous question, I am now struggling to pass the values of my radio buttons to my JavaScript function.
The desired output is to have both a 'BMR' value, and a 'recommended caloric intake' value, which is simply BMR x activity multiplier.
Here is both my JavaScript and HTML:
JavaScript
<script>
function calcCals() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let activity = document.getElementById("activity").value;
let calories;
let BMR;
// Calculate BMR
if (gender == 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
// Calculate Calories
if (activity == '1') {
calories = BMR * 1.2
} if (activity == '2') {
calories = BMR * 1.375
} if (activity == '3') {
calories = BMR * 1.55
} if activity == '4' {
calories = BMR * 1.725
} if activity == '5' {
calories = BMR * 1.9
}
console.log(BMR);
document.getElementById("bmrOutput").textContent = "Your BMR is " + BMR;
document.getElementById("calorieNeedsOutput").textContent = "Your Caloric Needs are " + calories;
event.preventDefault();
return;
}
</script>
HTML
<!--Enter Age and Gender-->
<h4>Age & Gender</h4>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="range" id="age" name="amountRange" min="16" max="80" value="30" oninput="this.form.amountInput.value=this.value">
<input type="number" id="age" name="amountInput" min="16" max="80" value="30" oninput="this.form.amountRange.value=this.value">
<!--Enter Height and Weight-->
<h4>Your Measurements</h4>
<input type="number" id="weight" placeholder="Weight in KG" required>
<input type="number" id="height" placeholder="Height in CM" required>
<!--Enter Activity Levels-->
<h4>Your Activity Level</h4>
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<!--Enter Goal and Contact Info-->
<h4>Your Goal + Contact Info</h4>
<input type="text" placeholder="What is your name?">
<input type="email" placeholder="Where shall we send your results?">
<select name="goal" id="goal">
<option value="lose">Lose Weight</option>
<option value="gain">Gain Muscle</option>
<option value="maintain">Maintain</option>
</select>
<!--Submit Button-->
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="bmrOutput"></p>
<p id="calorieNeedsOutput"></p>
</section>

In this solution I simplified the source code to read the radio button. When the submit button is clicked, the value of the selected radio button item is printed to the console. You can improve its algorithm by reading the value of the selected radio button element using the following approach.
let submitButton = document.getElementById('submitBtn');
submitButton.addEventListener('click', function() {
/* The value of the selected radio button element whose "name" attribute is "activity" from the <input> elements is assigned to the "activity" variable. */
let activity = document.querySelector('input[name="activity"]:checked').value;
console.log(`Activity: ${activity}`);
});
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<!--Submit Button-->
<button type="submit" id="submitBtn">Do Magic!</button>
The code snippet below shows the above solution applied to your code. For testing purposes, I removed the <form> element so that it would not submit after the button was clicked, and I made the click event fire for the button.
let submitButton = document.getElementById('submitBtn');
let firstAgeInput = document.getElementById('age1');
let secondAgeInput = document.getElementById('age2');
let gender = document.getElementById("gender");
let weightKG = document.getElementById("weight");
let heightCM = document.getElementById("height");
let age = document.getElementById('age1').value;
let bmrOutput = document.getElementById("bmrOutput");
let calorieNeedsOutput = document.getElementById("calorieNeedsOutput");
let ageInputs = document.querySelectorAll('.ageInputs');
/* Fields that may be null or empty should be checked for the calculation. */
function isValid() {
let activity = document.querySelector('input[name="activity"]:checked');
if(activity != null && weightKG.value.length != 0 && heightCM.value.length != 0)
return true;
return false;
}
/* This method updates the age value bidirectionally. */
function updateAge(newValue) {
secondAgeInput.value = newValue;
firstAgeInput.value = newValue;
}
/* Elements with the ".ageInputs" class style apply an input event. */
ageInputs.forEach(function(item, index) {
item.addEventListener('input', function() {
updateAge(this.value);
});
});
/* When the Submit button is clicked, this event is triggered and the result is printed to the HTML document. */
submitButton.addEventListener('click', function() {
if(isValid()) {
let activity = document.querySelector('input[name="activity"]:checked');
const bmrConstant = [1.2, 1.375, 1.55, 1.725, 1.9];
let calories, BMR = 10 * weightKG.value + 6.25 * heightCM.value - 5 * age;
(gender.value === 'male') ? (BMR += 5) : (BMR -= 161);
calories = BMR * bmrConstant[parseInt(activity.value) - 1];
bmrOutput.textContent = "Your BMR is " + BMR;
calorieNeedsOutput.textContent = "Your Caloric Needs are " + calories;
}
else
console.log("Fill in the blank fields in the form.");
});
<h4>Age & Gender</h4>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<!-- Items with the same id should not be used; therefore the following two items have been edited. -->
<input class="ageInputs" type="range" id="age1" name="amountRange" min="16" max="80" value="30">
<input class="ageInputs" type="number" id="age2" name="amountInput" min="16" max="80" value="30">
<h4>Your Measurements</h4>
<input type="number" id="weight" placeholder="Weight in KG" required>
<input type="number" id="height" placeholder="Height in CM" required>
<h4>Your Activity Level</h4>
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<h4>Your Goal + Contact Info</h4>
<input type="text" placeholder="What is your name?">
<input type="email" placeholder="Where shall we send your results?">
<select name="goal" id="goal">
<option value="lose">Lose Weight</option>
<option value="gain">Gain Muscle</option>
<option value="maintain">Maintain</option>
</select>
<button id="submitBtn">Do Magic!</button>
<p id="bmrOutput"></p>
<p id="calorieNeedsOutput"></p>

Related

Calculate percentage function

Struggling to get the desired results, code to test
The first two functions work, but the third one for the discount does not.
Depending on the number I put in the input field it should apply a discount up to 20% max on increments of 5,(so 1 = 5%, 2 = 10%, etc). No matter the value I put in the input field (deadline) value is stuck in applying the 20% discount. Full bit for testing:
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.querySelector("#servicePrice");
if (service_prices[selectedOption.value]) {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBoxes = form.querySelectorAll("#selectedBox");
selectedBoxes.forEach((box) => {
if (box.checked == true) {
extraPrices += 400;
}
});
return extraPrices;
}
//discount calc
const getDiscountPercent = (months) => (months < 4 ? months * 0.05 : 0.2);
const getTotal = (servicePrice, extraPrice, months) => {
const disTotal = servicePrice + extraPrice;
const discountPercent = getDiscountPercent(months);
return disTotal - disTotal * discountPercent;
};
//total final calc//
function Total() {
var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent();
document.getElementById("result").value = "€" + finalPrice;
}
<form action="" id="formulario" name="formulario">
<p> Type of Service
</p>
<select name="serviço" id="servicePrice" onchange="Total()">
<option value="none">Select a service
</option>
<option value="1500">1500€
</option>
<option value="4000">4000€
</option>
<option value="8000">8000€
</option>
</select>
<br>
<p>Deadline (months)
</p>
<input type="number" class="InStyle" id="months" name="months" onkeydown="Total()">
<br>
<!--checkbox-->
<h1>DESIRED EXTRAS
</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="Total()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="Total()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="Total()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="Total()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="Total()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="Total()"> News
<br>
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="Total()"> Social Network
<br>
<br>
<br>
<!--result-->
<h1>Estimated Total
</h1>
<input type="text" class="InStyle" disabled id="result">
</form>
You are not passing the months amount to getDiscountPercent function, neither taking months value from the input and also I advice you to use onChange event on month input .
function Total() {
var months = parseInt(document.querySelector('#months').value);
var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent(months);
document.getElementById("result").value = "€" + finalPrice;
}

Uncaught ReferenceError: function is not defined. Onclick/ onChange

TL;DR
getTotal should give me a total of these 2 functions summed together but it's throwing me an error instead:
Uncaught ReferenceError: getTotal is not defined
onchange http://127.0.0.1:3211/XyZPage/Untitled-1.html:1
Uncaught ReferenceError: getTotal is not defined
onclick http://127.0.0.1:3211/XyZPage/Untitled-1.html:1
code:
var service_prices= new Array();
service_prices=["0"]= 0;
service_prices=["1500"]= 1500;
service_prices=["4000"]= 4000;
service_prices=["8000"]= 8000;
function getServicePrice(){
var serviceOptionPrice=0;
var form = document.forms["formulario"];
var selectedOption = form.elements["servicePrice"];
serviceOptionPrice = service_prices[selectedOption.value];
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices(){
var extraPrices=0;
var form=document.forms["formulario"];
var selectedBox = form.elements["selectedBox"];
if(selectedBox.checked==true){
extraPrices=400;
}
return extraPrices;
}
//total final calc//
function getTotal(){
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").innerHTML= "eddies" + finalPrice;
}
I've tried couple fixes from threads here but nothing worked so far. JS alongside html https://jsfiddle.net/j1t68npf/
You have a several syntax errors in your JS which prevent the parser from reaching the getTotal() definition. So it remains undefined.
The offending sections is:
service_prices=["0"]= 0;
service_prices=["1500"]= 1500;
service_prices=["4000"]= 4000;
service_prices=["8000"]= 8000;
If you repair this you will no longer get the undefined error.
After this is fixed there are several other coding errors which, when resolved will get you this:
//reference the form by it's ID//
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.querySelector("#servicePrice");
if (service_prices[selectedOption.value]) {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBoxes = form.querySelectorAll("#selectedBox");
selectedBoxes.forEach(box => {
if (box.checked == true) {
extraPrices += 400;
}
})
return extraPrices;
}
//total final calc//
function getTotal() {
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").value = "eddies" + finalPrice;
}
<form id="formulario">
<p> Type of Service</p>
<select name="serviço" id="servicePrice" onchange="getTotal()">
<option value="none">Select a service</option>
<option value="1500">1500€</option>
<option value="4000">4000€</option>
<option value="8000">8000€</option>
</select>
<!--checkbox-->
<h1>DESIRED EXTRAS</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="getTotal()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="getTotal()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="getTotal()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="getTotal()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="getTotal()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="getTotal()"> News
<br>
<input type="checkbox" name="selectedBox"> Social Network
<br> <br> <br>
<!--result-->
<h1>Estimated Total</h1>
<input type="text" class="InStyle" disabled id="result">
</form>
It bears mentioning that you should not re-use ID values in html, they are supposed to be unique.
This is a corrected version of your code, as stated in comments there were multiple syntax errors, but most importantly, you're handling the checkbox collection as if it were a single checkbox.
In this version I iterate all checkboxes and accumulate 400 for each checked one.
//reference the form by it's ID//
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.elements["servicePrice"];
if (selectedOption.value != "none") {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBox = form.elements["selectedBox"];
selectedBox.forEach(el => {
if (el.checked) {
extraPrices += 400;
}
})
return extraPrices;
}
//total final calc//
function getTotal() {
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").value = "eddies" + finalPrice;
}
<form id="formulario" name="formulario">
<p> Type of Service</p>
<select name="serviço" id="servicePrice" onchange="getTotal()">
<option value="none">Select a service</option>
<option value="1500">1500€</option>
<option value="4000">4000€</option>
<option value="8000">8000€</option>
</select>
<!--checkbox-->
<h1>DESIRED EXTRAS</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="getTotal()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="getTotal()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="getTotal()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="getTotal()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="getTotal()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="getTotal()"> News
<br>
<input type="checkbox" name="selectedBox"> Social Network
<br> <br> <br>
<!--result-->
<h1>Estimated Total</h1>
<input type="text" class="InStyle" disabled id="result">
</form>

Output from the radio button into JavaScript doesn't work

I am doing a simple online form to calculate BMR using Harris–Benedict equation with the imperial measurements. I don't know where the error is inside my code but right now only the Clear the form button works. I didn't post the entire HTML code for the webpage because it looks just like I want it and it's only the calculation that I am having the problem with.
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="maleinput" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="femaleinput" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementById("gender").value;
if (genderIm.value = "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
document.getElementById("button").addEventListener("submit", impCalc, false);
The radio button were not working because you were taking them as an ID but the id does not exist in the input. You have get them via getElementsByName()[0]
Also you event listener did not know where button is clicked so the button id is is unique and it will listen to that click only when you click submit.
Here is working demo: https://jsfiddle.net/usmanmunir/tjsnaz4w/10/
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementsByName("gender")[0].value
if (genderIm.value == "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
var el = document.getElementById('submit');
el.addEventListener("click", impCalc, false);
HTML
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="gender" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="gender" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
Hope this helps.

Javascript not adding selected values in radio buttons when running function

I have created a test website to learn some js by making an online store than basically has values in a form
what i am stuck on is when my html calls the function on shipping
its not adding the shipping properly (only for ground which seems to be defaulted to)
I need the ability for the script to calculate the proper shipping charge depending on radio button selected
function calcTaxes() {
cost = 10;
var taxed = cost * document.getElementById("qty").value;
var freight = document.getElementById("shipping").value;
var freightNum = parseInt(freight, 10);
var totalCost;
if (taxed < 10){
taxed = (taxed * .1) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
else if (taxed > 10 && taxed < 20){
taxed = (taxed * .0725) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
else {
taxed = (taxed * .05) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
}
<h2>Order Form -- T-shirts $10 each</h2>
<br>
<form>
Name: <input type="text" placeholder="Your name here" ><br><br>
Address: <textarea placeholder="Your Address"></textarea><br><br>
Email: <input type="email" placeholder="Your email address" ><br><br>
<label for="size">Choose a size: (Same Price) </label>
<select id="size" name="size">
<option value="XS">XS -Extra Small</option>
<option value="S">S-Small</option>
<option value="M">M-Medium</option>
<option value="L">L-Large</option>
<option value="XL">XL-Extra Large</option>
<option value="XXL">XXL-Extra Extra Large</option>
</select><br><br>
Color: <input type="radio" value="Black" name="color">Black
<input type="radio" value="White" name="color">White
<input type="radio" value="Gun-Metal" name="color">Gun-Metal
<br><br>
Quantity: <input id="qty" type="number"><br><br>
Shipping: <input type="radio" value= "10" id="shipping" name="shipp">Ground ($10)
<input type="radio" value="20" id="shipping" name="shipp" >Overnight ($20)
<input type="radio" value="25" id="shipping" name="shipp" >Drone-Drop ($25)
<br><br>
<br>
</form>
<button class="taxes" onclick="calcTaxes()">Calculate Total</button><br>
Includes shipping and taxes:<p id="tax"></p>
</body>
</html>
The problem is that you are using document.getElementById which will always return the first element with I'd shipping.
Try using document.getElementsByName
Remember it'll return an array of elements
You'll need to get the value from the current selected radio button, for example, you could do:
var freight = document.querySelector('input[name="shipp"]:checked').value;
function calcTaxes() {
cost = 10;
var taxed = cost * document.getElementById("qty").value;
var freight = document.querySelector(`input[name="shipp"]:checked`)
.value;
var freightNum = parseInt(freight, 10);
var totalCost;
if (taxed < 10) {
taxed = taxed * 0.1 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
} else if (taxed > 10 && taxed < 20) {
taxed = taxed * 0.0725 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
} else {
taxed = taxed * 0.05 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
}
}
<h2>Order Form -- T-shirts $10 each</h2>
<br />
<form>
Name: <input type="text" placeholder="Your name here" /><br /><br /> Address: <textarea placeholder="Your Address"></textarea><br /><br /> Email: <input type="email" placeholder="Your email address" /><br /><br />
<label for="size">Choose a size: (Same Price) </label>
<select id="size" name="size">
<option value="XS">XS -Extra Small</option>
<option value="S">S-Small</option>
<option value="M">M-Medium</option>
<option value="L">L-Large</option>
<option value="XL">XL-Extra Large</option>
<option value="XXL">XXL-Extra Extra Large</option>
</select><br /><br /> Color: <input type="radio" value="Black" name="color" />Black
<input type="radio" value="White" name="color" />White
<input type="radio" value="Gun-Metal" name="color" />Gun-Metal
<br /><br /> Quantity: <input id="qty" type="number" /><br /><br /> Shipping:
<input type="radio" value="10" id="shipping" name="shipp" />Ground ($10)
<input type="radio" value="20" id="shipping" name="shipp" />Overnight ($20)
<input type="radio" value="25" id="shipping" name="shipp" />Drone-Drop ($25) <br /><br />
<br />
</form>
<button class="taxes" onclick="calcTaxes()">Calculate Total</button><br /> Includes shipping and taxes:
<p id="tax"></p>
So what I can see the freight value is being assigned the first value since it's calling the first id with the name shipping with document.getElementById('shipping').
You could assign each radio button with an onclick="myShippingCost(this.value)" and in your JS, call that function if your main calcTaxes().
Example:
var radioValue;
myShippingCost(value) {
radioValue = value;
}
calcTaxes() {
// ...your code
var freight = radioValue;
// ...your code
}

Radio Button Javascript

I have radiobuttons like below:
Apple
<input type="radio" id="one" name="apple" data-price="10" value="light"/> Light
<input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark
<input type="text" id="appleqty" name="appleqty" value="" />
Mango
<input type="radio" id="three" name="Mango" data-price="30" value="light"/> Light
<input type="radio" id="one" name="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
Pine Apple
<input type="radio" id="four" name="Pineapple" data-price="50" value="light"/> Light
<input type="radio" id="five" name="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
Grape
<input type="radio" id="six" name="Grape" data-price="70" value="light"/> Light
<input type="radio" id="seven" name="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
​
The radiobuttons are separated in a Group as (Apple,Mango,Pineapple,Grape).
I need to add the Price with the Quantity he needs.
Example:
If a user clicked Dark Apple in the radiobutton with 1 Qty the Price should be 20 and if the user changed the clicked Radio to the Light Apple radiobutton then the price should be 10 - 20(Previous Price If Checked) = 10 .
Is this possible using JavaScript?
My code that I have tried:
function upprice(ref)
{
var elname = ref.getAttribute("name");
var qtyname = elname+"qty";
var price = ref.getAttribute("proprice");
var qty = parseInt(document.getElementById(qtyname).value)
var newprice = parseInt(price*qty);
var olprice = parseInt(document.getElementById("orderpagepriceinstant").innerHTML);
var totalprice = parseInt(olprice+newprice);
document.getElementById("orderpagepriceinstant").innerHTML = parseInt(totalprice)
}
Your inputs should be something like:
<input type="radio" name="apple" value="10">Light
<input type="radio" name="apple" value="20">Dark
<input type="text" name="appleqty" value="">
You can put a click listener on the radio buttons and a change listener on the quantity to update the price:
<input type="radio" onclick="updatePrice(this)" ...>
<input type="text" onclick="updatePrice(this)" ...>
and the update function is:
function updatePrice(el) {
var priceEach, quantity, itemValue;
if (el.type == 'radio') {
priceEach = getRBValue(el);
quantity = el.form[el.name + 'qty'].value;
} else if (el.type == 'text') {
quantity = el.value;
priceEach = getRBValue(el.form[el.name.replace(/qty$/,'')]);
}
/*
code here to validate the value of quantity
*/
itemValue = quantity * priceEach;
/*
do something with itemValue
*/
alert(itemValue);
}
// Get the value of a radio button set
function getRBValue(el) {
var buttons;
// See if have been passed a button or button set (NodeList)
if (el.type == 'radio') {
buttons = el.form[el.name];
} else if (typeof el.length == 'number') {
buttons = el;
}
if (buttons) {
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
}
</script>
The markup, you can also add a click listener to the form to do updates rather than on each radio button. You should also have a reset button so the user can clear the form.
<form ... >
<input type="radio" name="apple" value="10" onclick="updatePrice(this)">Light
<input type="radio" name="apple" value="20" onclick="updatePrice(this)">Dark
<input type="text" name="appleqty" value="" onchange="updatePrice(this)">
<br>
<input type="reset">
</form>
Here's a quick jQuery example: http://jsfiddle.net/FTscC/
(laptop dying, I'll elaborate when I can tomorrow!)

Categories