Adding value of selected radio button to an equation - javascript

I am at my wits end. I cannot figure out how to add the value of the radio button to the equation. Can someone give me a clue at least on this??
If I don't have the radio button function included, this works fine.
<input type="radio" class="InternetCost" name="int" id="no_int" value="0">None<br>
<input type="radio" class="InternetCost" name="int" id="ten" value="10">10<br>
<input type="radio" class="InternetCost" name="int" id="twenty" value="20">20<br>
<input type="radio" class="InternetCost" name="int" id="thirty" value="30">30<br>
//Try to select radio button
var values = document.getElementsByName("int");
function getValue() {
for(var i = 0; i < values.length; i++) {
if(values[i].checked == true) {
selectedValue = values[i].value;
console.log('value=' + selectedValue);
}
}
}
function calculate()
{
//get selectedValue - this is where I am lost!
var radioValue = getValue()*1;
//Package
var pkgCost = document.getElementById("pkg").value*1;
//Package - Static
var equipPkg = document.getElementById("pep").value*1;
//Additional amount
var addBox = document.getElementById("addtl").value*1;
//Additional Box cost - static
var totalNum = document.getElementById("add_cost").value*1;
//Service amount
var dvrSvc = document.getElementById("dvr_svc").value*1;
//Service cost - static
var dvrCost = document.getElementById("dvr_cost").value*1;
// Sum everything
var SumAll = pkgCost + equipPkg + (addBox*totalNum) + (Svc*Cost) + radioValue;
// print the total
document.getElementById("Sum").innerHTML = SumAll.toFixed(2)
}

Your solution should work fine except you're using
console.log('value=' + selectedValue);
instead of actually returning the value.
return selectedValue;
Example

Related

How to implement an if-statement in an order form

I'm building a simple order form with some calculations with number & hidden fields (for email and autoresponder).
When the user input field is not '0' i want it to calculate the delivery cost in the total price. In the script below the Delivery cost always returns '0' even when the user field is not '0'.
If I change the value to a certain value it always returns that value even when the user field is '0'. So the IF is wrong somehow.
/* Get the values from the user*/
function getAantal() {
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
/* Product variables*/
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
/* Delivery variables, Soundtrack does not have delivery*/
/* in my logic the IF says: if user fills in 0 for AantalBoek,
then VerzendingBoek is 0 instead of 7. But it always returns 0, even if AantalBoek is 1*/
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
if (AantalBoek !== null && AantalBoek !== '') {
VerzendingBoek = 0;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if (AantalCD !== null && AantalCD !== '') {
VerzendingCD = 0;
}
/* Calculation of the Product total*/
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
/* Calculation of the Delivery total*/
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
/* Calculation of the Final total*/
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value = TotaalVerzending;
document.getElementById('TotaalPrijs').value = Totaal;
}
<!-- user defines values here: -->
<input type="number" id="AantalBoek" required="" onchange="getAantal()">
<input type="number" id="AantalCD" required="" onchange="getAantal()">
<input type="number" id="AantalSoundtrack" required="" onchange="getAantal()">
<!-- set values for the products: -->
<input type="hidden" id="PrijsBoek" name="PrijsBoek" value="15">
<input type="hidden" id="PrijsCD" name="PrijsCD" value="4">
<input type="hidden" id="PrijsSoundtrack" name="PrijsSoundtrack" value="2">
<!-- set values for the delivery cost: -->
<input type="hidden" id="VerzendingBoek" name="VerzendingBoek" value="7">
<input type="hidden" id="VerzendingCD" name="VerzendingCD" value="2">
<!-- totals are shown here (only for autorespond) -->
<input type="hidden" id="Verzending" name="Verzending">
<input type="hidden" id="TotaalPrijs" name="TotaalPrijs">
Ok i've started over, looking again at the if-statement and i found a syntax error, changed the condition and added an else statement.
The corrected script is this:
function getAantal(){
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
/* Here I changed the condition: IF the user value is 0 then the delivery cost is 0,
ELSE use the value that was already defined:*/
if(AantalBoek == 0) { VerzendingBoek = 0;
} else {VerzendingBoek = document.getElementById('VerzendingBoek').value;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if(AantalCD == 0) { VerzendingCD = 0;
} else {VerzendingCD = document.getElementById('VerzendingCD').value;
}
/*for the second condition i corrected the syntax error !== to !=,
IF delivery cost for Boek is not 0, then delivery cost for CD is 0*/
if (VerzendingBoek != 0) { VerzendingCD = 0;
}
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value=TotaalVerzending;
document.getElementById('TotaalPrijs').value=Totaal;
}

start a function if another function is active and activate some checkboxes only - JQuery

i Have a function that I want to start only if another function is previously activated.
I have some CheckBoxes and I need to sum its values to get the total.
Only When a user has selected some of the CheckBoxes it must activate another checkbox with a discount.
I want that the discount checkbox get activated after the first selection because, if I don't do so, I could have a negative price.
Then (if it's possible) I want that the discount checkbox get deactivated is a user deselect all the previous CheckBoxes.
Is this possible?
Here's my script. I'm super new in JavaScript/jQuery so this might be a stupid question.
Thank you
$(document).on('change', getCheck);
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
//console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
//console.log(total);
//console.log(price_tot);
$('#rata').text(total +" €");
var finalprice = total;
//var Check = getCheck();
if(typeof(total) != "undefined" && total !== 0) {
$('[type="checkbox"]:checked').not(".sum").each(function(i, el) {
var Discount = parseFloat($(this).val());
finalprice = finalprice - Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
});
};
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="sum" type="checkbox" name="vehicle1" value="1000"> I have a bike<br>
<input class="sum" type="checkbox" name="vehicle2" value="2000"> I have a car<br>
<br><br><br>
<input id="discount" type="checkbox" name="discount" value="200"> Discount<br>
<div id="rata">rata</div>
Replace your js code with this code. the error will be resolved.
$( document ).ready(function() {
$("input[type='checkbox']").on('change', getCheck);
});
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
console.log(total);
//console.log(price_tot);
$('#rata').html(total +" €");
var finalprice = total;
var Check = function getCheck(){
if(typeof(Check) != "undefined" && Check !== null) {
$("#discount").toggle();
var Discount = parseFloat($(this).val());
finalprice -= Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
};
};
});
};

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

Calculating totals when clicking checkboxes

I have a list of radio buttons represented by this code:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
Whenever a button is selected I need the subtotal and total to be updated.
This is how i want it to look.
Subtotal: <br />
Tax:<br />
Total:<br />
Where tax is always %7 or .7
The prices of menu 1 through 7 increments by $5. Menu1 is $5, menu2 is $10 and so forth.
I was trying to figure out the JavaScript to this but the problem is that i don't want it to display right after the buttons I want it displayed on the bottom of the page.
If I do document.write the whole page gets overwritten. Please help me on this issue guys. I am sure it's really simple.
Preamble
This sounds like homework to me. However, I find that the best way to learn, is by example.
So here's me, leading by example, OK?
You didn't give me much to go on, so for the sake of this example, I'm assuming you've got a list of checkboxes or radiobuttons that say Menu 1... Menu n. Each checkbox that is checked will be added to the subtotal, and then the tax calculated on top of that.
Doing it with radio buttons is a little easier, so I added that example as well.
On the bottom of the post are references for future study on what is used in this example.
If you have any further questions please ask them in the comment area at the bottom of this post.
The Javascript (checkboxes) | JSFiddle example (see it in action)
//Set the tax and base cost
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_checkboxes = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_checkboxes.length; i++){
e_checkboxes[i].onchange = function(){
//Recalculate subtotal
get_subtotal();
}
}
//get_subtotal calculates the subtotal based on which checkboxes are checked
function get_subtotal(){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
for(var i = 1; i <= e_checkboxes.length; i++){
//If the checkbox is checked, add it to the total
if(e_checkboxes[i-1].checked){
f_sub_total += i * i_menu_base;
}
}
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the display element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
The Javascript (radio buttons) | JSFiddle example (see it in action)
//Set the tax
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_radios = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_radios.length; i++){
e_radios[i].onchange = function(){
//Recalculate subtotal
get_subtotal(this);
}
}
//get_index gets the index of the element (1..n)
function get_index(element){
for(var i = 1; i <= e_radios.length; i++){
if(e_radios[i-1] == element){
return i;
}
}
}
//get_subtotal calculates the subtotal based on the radio that was changed
function get_subtotal(el){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
f_sub_total += get_index(el) * i_menu_base
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
References for future study
In order in which they appear
getElementById()
getElementsByTagName()
looping through an array
onchange
Math.round(), decimal trick and toFixed()
innerHTML
Despite any additonal input from you, and my better judgement, I was bored so I did it all.
HTML:
<form id="menu4strombolis">input1
<input type="radio" name="menu1" value="5">
<br>input2
<input type="radio" name="menu2" value="10">
<br>input3
<input type="radio" name="menu3" value="15">
<br>input4
<input type="radio" name="menu4" value="20">
<br>input5
<input type="radio" name="menu5" value="25">
<br>input6
<input type="radio" name="menu6" value="30">
<br>input7
<input type="radio" name="menu7" value="35">
<br>
</form>
<button id="getTotal">Total</button>
<div id="subtotal">Sub-Total:</div>
<div id="tax">Tax:</div>
<div id="total">Total:</div>
JS:
var button = document.getElementById("getTotal");
button.onclick = function () {
var subtotalField = document.getElementById("subtotal");
var radios = document.forms["menu4strombolis"].getElementsByTagName("input");
var subtotal = 0;
var tax = 0;
var total = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
subtotal += parseInt(radios[i].value);
}
}
tax = (subtotal * .07).toFixed(2); ;
total = subtotal + tax;
document.getElementById("subtotal").innerHTML = "Sub-Total: $" + subtotal;
document.getElementById("tax").innerHTML = "Tax: $" + tax;
document.getElementById("total").innerHTML = "Total: $" + total;
};
and the working fiddle:
http://jsfiddle.net/RGvTt/1/
Though on a side note, you should either group some of the radios together in the same group... or make them checkboxs.
Updated to fix the bug that the OP couldn't fix:
http://jsfiddle.net/RGvTt/4/
Need to use parseFloat.
iPhone fiddle programming FTW!
What you want is element.innerHTML
So it would look something like this:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
..... ..html stuff here
Subtotal: <span id="subtotal"></span><br/>
Tax: <span id="tax"></span><br/>
Total: <span id="total"></span><br/>
ETC...
<script>
var subtotal = //whatever menu item is checked then .value();
var span_subtotal = document.getElementById("subtotal);
var tax = document.getElementById("tax");
var total = document.getElementById("total");
var the_tax = subtotal * .07;
span_subtotal.innerHTML = subtotal;
tax.innerHTML = the_tax;
total.innerHTML = subtotal + the_tax;
<script>

Shortening JavaScript Function

I must admit, I don't know much about JavaScript that is why my question might sound little bit silly.
But what I'm trying to do is grab values from selected by name radio groups.
It looks like this
function calc() {
var op1 = document.getElementsByName('form[radio1]');
var op2 = document.getElementsByName('form[radio2]');
var op3 = document.getElementsByName('form[radio3]');
var result = document.getElementById('result');
result.value = 0;
result.value = parseInt(result.value);
for (i = 0; i < op1.length; i++) {
if (op1[i].checked) result.value = parseInt(result.value) + parseInt(op1[i].value);
}
for (i = 0; i < op2.length; i++) {
if (op2.options[i].selected) result.value = parseInt(result.value) + parseInt(op2[i].value);
}
for (i = 0; i < op3.length; i++) {
if (op3.options[i].selected) result.value = parseInt(result.value) + parseInt(op3[i].value);
}
return false;
}
And this is my form. Im using rs form for joomla.
<form action="index.php" enctype="multipart/form-data" id="userForm" method="post">
<input name="form[radio1]" value="25" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio1]" value="35" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input name="form[radio2]" value="20" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio2]" value="30" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input type="hidden" value="0" id="result" name="form[result]">
<input type="submit" class="rsform-submit-button" onclick="calc()" id="submit" name="form[submit]" value="submit">
And everything would be OK, as the function is working. the only trouble is that I have about 80 radiograms.
Is there a way to shorten it?
Use arrays of objects (like all the radio buttons, for instance) and iterate over them. Start like this:
var opts = [],
numOpts = 80;
for (var i=0; i<numOpts, i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
Edit: let's have a go at the full function. The only thing I'm not 100% sure about is whether you mean to use opX[i].checked or opX.options[i].selected (since your code does different things for op1 and op2/3). Shouldn't be too hard to extrapolate if I've guessed wrong, though.
function calc()
{
var opts = [],
numOpts = 80,
value = 0,
result = document.getElementById('result'),
i, j, opt;
for (i=0; i<numOpts; i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
numOpts = opts.length;
for (i=0; i<numOpts; i++)
{
opt = opts[i];
for (j=0; j<opt.length; j++)
{
// or did you mean:
// if (opt.options[j].selected) ?
if (opt[j].checked)
{
value = value + parseInt(opt[j].value, 10);
}
}
}
result.value = value;
return false;
}
jQuery is a great library that's like using JavaScript on steroids. It is well worth learning and there are plenty of examples out in the wild.
You can write complex "selectors" quite like this:
$('input[name=form[radio1]]').attr('checked').each(function() {
result.value = $(this).attr('value')
})
(I'm not sure if it will accept a name like "form[radio1]" as valid, but give it a try.

Categories

Resources