Contribution margin percentage - javascript

I have made a formula to calculate contribution margin of a product, the thing is that the percentage is limited to 100%.
If we buy a product for 0.2€ and sell it for 99€, basically we earn more then 100% of the value.
$("#tb_calculator").change(function(){
$this = $(this);
var price_in = $this.find(".tb_price_in").val().replace(',', '.');
var price_out = $this.find(".tb_price_out").val().replace(',', '.');
var quantity = $this.find(".tb_quantity").val().replace(',', '.');
//var percentage = (price_out / price_in - 1)*100;
var percentage = (price_in / price_out);
var tb_value = (price_out*quantity - price_in*quantity);
//console.log(percentage);
var final_percentage = Math.round(((1-percentage)*100));
if (final_percentage === Infinity || final_percentage === "" || isNaN(final_percentage) || final_percentage < 0 || percentage < 0) {
var final_percentage = 0;
}
if (tb_value === Infinity || tb_value === "" || isNaN(tb_value)) {
var tb_value = 0;
}
function tofixed(val)
{
return parseFloat(val.toFixed(2));
}
$(".tb_count").val(tofixed(tb_value)+"kr - ("+final_percentage+"%)");
});
jsFiddle

Related

Javascript Function Calculate on grid does not working when running on Chrome or Edge but working fine on IE11

******* why amount and total field does not automatic calculate correctly, it's still be old value and not change by calculation ***
function Calculate(txtQty, txtPrice, txtAmount, txtTotal) {
var txtQtyObj = document.getElementById(txtQty).value != "" ? document.getElementById(txtQty).value : "0";
var txtPriceObj = document.getElementById(txtPrice).value != "" ? document.getElementById(txtPrice).value : "0";
var txtAmountObj = document.getElementById(txtAmount).value != "" ? document.getElementById(txtAmount).value : "0";
var txtTotalHideObj = document.getElementById(txtTotal).value != "" ? document.getElementById(txtTotal).value : "0";
var amount = txtAmountObj.replace(/,/g, '')
var Total = txtTotalHideObj.replace(/,/g, '')
if (txtPrice.value != '') {
txtAmountObj = parseFloat(txtQtyObj) * parseFloat(txtPriceObj);
} else {
txtAmountObj = ''
}
if (parseFloat(Total) > 0) {
var txtTotal1 = parseFloat(Total) - parseFloat(amount) + parseFloat(txtAmountObj);
document.getElementById(txtTotal).innerHTML = formatCurrency(txtTotal1);
}
else {
var txtTotal1 = parseFloat(Total) + parseFloat(txtAmountObj);
document.getElementById(txtTotal).innerHTML = formatCurrency(txtTotal1);
}
document.getElementById(txtAmount).innerText = formatCurrency(txtAmountObj);
}
**** Amount box #1 ****
*** Amount box #2 ***
*** Total box **

Passing id value to a variable not working, only returning itstrue

I tried to add 2 field value and compare it with dropdown value with JS but its not working with variable.
$(document).ready(function() {
$('#SAVE,#CREATE').mouseover(function(e) {
var value89 = $('#P315_THRESHOLD').val() || 0;
var value20 = parseFloat($('#P315_C_RELEASE_REQUEST').val()) || 0;
var value21 = parseFloat($('#P315_O_RELEASE_REQUEST').val()) || 0;
var valuetot3 = value20 + value21 ;
var str = "";
if( value89 = '>250' && valuetot3 < 250 )
{
alert('CAPEX and OPEX request total value should be greater than 250 , current total is' +$('#P315_THRESHOLD').val() || 0);
}
});
});
Expected result is that it should throw alert for the conditions.
if( value89 = '>250' && valuetot3 < 250 )
........................^ this is an affectation instead of a comparaison
Either use value89 === '>250' or value89 >= 250
This should work according to your condition. Just remove = '>250' and replace >=250
<script>
$(document).ready(function() {
$('#SAVE,#CREATE').mouseover(function(e) {
var value89 = $('#P315_THRESHOLD').val() || 0;
var value20 = parseFloat($('#P315_C_RELEASE_REQUEST').val()) || 0;
var value21 = parseFloat($('#P315_O_RELEASE_REQUEST').val()) || 0;
var valuetot3 = value20 + value21 ;
var str = "";
if( value89 >=250 && valuetot3 < 250 ){
alert('CAPEX and OPEX request total value should be greater than 250 , current total is' +$('#P315_THRESHOLD').val() || 0);
}
});
});
</script>

Too much recursion - radio button - jquery

I have a dynamic form and in that many fields I want to be autocalculated when user goes on with the form. In the form I have 2 radio button mrp and rate. By default mrp is selected. If user doesn't change the default button selected, the value totalCst will be calculated as qty*mrp*cstpercent of all the rows.
If user selects rate radiobutton the value will be calculated as qty*rate*cstpercent of all the rows. I'll add the onchange event later. First I want to get the value totalCst calculated on mrp only or rate whichever is selected.
Radio Button code -
<div class="form-group pull-right">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</div>
JS
<?php
/* start getting the total amount */
$this->registerJs('
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
var selectedValue = $("input[name=taxon]:checked").val();
alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
if (selectedValue == "mrp") {
getSum();
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
$(".totalCst").val(totalCstonamount);
}
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
I'm getting the value selected in alert but too many popup and getting error -
Too much recursion
Updated JS
<?php
/* start getting the total amount */
$this->registerJs('
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
// var totalCstonamount = 0;
// var totalWbstonamount = 0;
// var totalCstonmrp = 0;
// var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
//var selectedValue = $("input[name=taxon]:checked").val();
//alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
// if (selectedValue == "mrp") {
// getSum();
// $(".totalCst").val(totalCstonmrp);
// }
// else if (selectedValue == "rate") {
// getSum();
// $(".totalCst").val(totalCstonamount);
// }
}
function getSumonclick(){
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
getSum();
var selectedValue = $("input[name=taxon]:checked").val();
// var totalCstonamount = 200;
// var totalWbstonamount = 0;
// var totalCstonmrp = 100;
// var totalWbstonmrp = 0;
if (selectedValue == "mrp") {
getSum();
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
$(".totalCst").val(totalCstonamount);
}
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
As per my understanding, Now the issue turns out to be to get the calculated values from inside of getSum function to outside of it.
First I want to get the value totalCst calculated on mrp only or rate
whichever is selected.
You can use the ternary operator here, rather than if... else...:
var factor = (factorMrp.checked ? 'mrp' : 'rate');
Working Example:
var factors = document.getElementById('factors');
var factorMrp = document.getElementById('mrp');
var factorRate = document.getElementById('rate');
var paragraph = document.getElementsByTagName('p')[0];
factorMrp.checked = true;
function checkFactor() {
var factor = (factorMrp.checked ? 'mrp' : 'rate');
paragraph.textContent = 'The value totalCst will be calculated as qty * ' + factor + ' * cstpercent of all the rows.';
}
factors.addEventListener('change',checkFactor,false);
window.addEventListener('load',checkFactor,false);
fieldset {
display: inline-block;
}
<form>
<fieldset id="factors">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</fieldset>
</form>
<p></p>

Canvas not graphing exponents or multiple lines correctly

I have a program that graphs a line on an HTML canvas with JavaScript. The HTML contains a 500px by 500px canvas and a div with the id "LineBoxHolder" that has a certain number of items inside, which are from zero to infinity select elements of the class .equation, and for each one, depending on the selected value, a number of inputs of the type number and the class .eqNum. Here's a chart to clarify that part:
selected value | number of "number" inputs added
------------------------------------------------
number | 1
linear | 2
quadratic | 3
power | 2
exponential | 2
For example, if you have 3 select boxes, 1 with "linear" selected and 2 with "quadratic" selected, you get a total of 8 ".eqNum" inputs. Sorry if I'm not making much sense, I'ts midnight and I've had lots of homework lately (8th grade), but if this is too confusing I'll clean it up and add a bounty tomorrow. Anyways, here's the JavaScript code simplified down to what I think is the most important part. My problem, by the way, is that I can't graph multiple lines, and all types of lines except "number" and "linear" show up oddly.
function DrawCurrent()
{
//Set up environment
var cnvs = document.getElementById("cnvs");
cnvs.height = 500;
cnvs.width = 500;
var cont = cnvs.getContext("2d");
var imdt = cont.getImageData(0,0,500,500);
//Get the rest of the dimension and color values that need to be tested
var canvasXmin = document.getElementById("CanvasX-min").value;
var canvasYmin = document.getElementById("CanvasY-min").value;
var canvasXmax = document.getElementById("CanvasX-max").value;
var canvasYmax = document.getElementById("CanvasY-max").value;
var x_minList = document.querySelectorAll("#LineBoxHolder .x-min");
var y_minList = document.querySelectorAll("#LineBoxHolder .y-min");
var x_maxList = document.querySelectorAll("#LineBoxHolder .x-max");
var y_maxList = document.querySelectorAll("#LineBoxHolder .y-max");
var rgbaValue = document.querySelectorAll("#LineBoxHolder .lineColor");
var xyList = document.querySelectorAll("#LineBoxHolder .xOry");
var eqList = document.querySelectorAll("#LineBoxHolder .equation");
var numList = document.querySelectorAll("#LineBoxHolder .eqNum");
//Create variables to be used in graphing (Not all are nessecary, but they make for less repetitive and pointless coding)
var pseudoBase = 0;
var baseList = [];
var pseudoDependent = 0;
var pseudoDependentList = [];
var actualDependentList = [];
var dependentActual = 0;
var xMin = 0;
var xMax = 0;
var yMin = 0;
var yMax = 0;
var eqtn = "";
var numListNum = 0;
var a = 0;
var b = 0;
var c = 0;
var index = 0;
//Graph the lines
for (var z9 = 0 ; z9 < eqList.length/*Eqlist has 1 value for each line, so its length is equal to the number of lines*/ ; z9++ )
{
//Set values
xMin = x_minList[z9].value*1;
xMax = x_maxList[z9].value*1;
yMin = y_minList[z9].value*1;
yMax = y_maxList[z9].value*1;
eqtn = eqList[z9].value;
for ( var z10 = 0 ; z10 < 500 ; z10++ )
{
pseudoBase = canvasXmin*1 + (((Math.abs( canvasXmax - canvasXmin )) * z10)/500);
if ( pseudoBase >= xMin && pseudoBase <= xMax )
{
baseList.push( pseudoBase );
}
else
{
baseList.push( NaN );
};
}
if ( eqtn == "number" )
{
a = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = a;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax)
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push( NaN);
};
}
}
if ( eqtn == "linear" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a*baseList[z12])*1 + b*1;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "quadratic" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
c = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(baseList[z12],2))+(b*1*baseList[z12])+c*1;
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "power" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(baseList[z12],b));
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
if ( eqtn == "exponential" )
{
a = numList[numListNum].value;
numListNum++;
b = numList[numListNum].value;
numListNum++;
for ( var z12 = 0 ; z12 < 500 ; z12++)
{
pseudoDependent = (a* Math.pow(b,baseList[z12]));
if ( pseudoDependent >= yMin && pseudoDependent <= yMax )
{
pseudoDependentList.push(pseudoDependent);
}
else
{
pseudoDependentList.push(NaN);
};
}
}
for ( var z13 = 0 ; z13 < 500 ; z13++ )
{
dependentActual = 500-(((pseudoDependentList[z13]*1 + (0 - canvasYmin*1))*500)/Math.abs(canvasYmax-canvasYmin));
actualDependentList.push(dependentActual);
}
var storedindex = 0;
var currentIndex = 0;
for ( var z14 = 0 ; z14 < 500 ; z14++)
{
currentIndex = parseInt(Math.round((actualDependentList[z14]*2000) + (4*z14)));
console.log(currentIndex + " " + actualDependentList[z14] + " " + z14);
if (currentIndex >= 0 && currentIndex <= 999997 && pseudoDependentList[z14] != NaN && baseList[z14] != NaN)
{
environment.data[currentIndex] = newColorList[z9];
environment.data[currentIndex + 1] = newColorList[z9+1];
environment.data[currentIndex + 2] = newColorList[z9+2];
environment.data[currentIndex + 3] = 255;
}
if ( z14 > 0 && currentIndex < storedY && pseudoDependentList[z14] != NaN && baseList[z14] != NaN)
{
for ( var z20 = 1 ; z20 < Math.floor((storedY-currentIndex)/2000) ; z20++ )
{
index = currentIndex + (z20*2000);
if ( index < 999997 && index > 0 )
{
environment.data[index] = newColorList[z9];
environment.data[index + 1 ] = newColorList[z9+1];
environment.data[index + 2 ] = newColorList[z9+2];
environment.data[index + 3 ] = 255;
}
}
}
if ( z14 > 0 && currentIndex > storedY && pseudoDependentList[z14] != NaN && baseList[z14] != NaN )
{
for ( var z15 = 0 ; z15 < Math.floor((currentIndex-storedY)/2000) ; z15++ )
{
index = currentIndex + (z15*2000);
if ( index < 999997 && index > 0 )
{
environment.data[index] = newColorList[z9];
environment.data[index + 1 ] = newColorList[z9+1];
environment.data[index + 2 ] = newColorList[z9+2];
environment.data[index + 3 ] = 255;
}
}
}
storedY = currentIndex;
}
}
pixelDotter.putImageData( environment , 0 , 0 );
}
Also here's some sample HTML in case I was confusing:
<body onload = drawCurrent()>
<canvas id = "cnvs" height = "500px" width = "500px">
</canvas>
<div id = 'LineBoxHolder'>
<select class = "equation">
<option value = 'number'>A</option>
<option value = 'linear' selected = 'selected'>B</option>
<option value = 'quadratic'>C</option>
<option value = 'power'>D</option>
<option value = 'exponential'>E</option>
</select>
<!--Linear is selected so there are 2 number inputs-->
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
<select class = "equation">
<option value = 'number'>A</option>
<option value = 'linear' >B</option>
<option value = 'quadratic' selected = 'selected'>C</option>
<option value = 'power'>D</option>
<option value = 'exponential'>E</option>
</select>
<!-- Quadratic is selected so there are 23 number inputs-->
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
<input type = 'number' class = "eqNum">
</div>
Last quick note, JavaScript code assumes theres at least 1 line and that all the values it tries to get from html exist somewhere and are valid.

Add Variables In If Statement From Values Determined by Radio Buttons

I have a short survey that gives a final value based on the selections you make. The problem is, only the first radio group, "people" is being added at the end... the other four (org + focal + location + carry) are being ignored. Would someone please help me figure out what is wrong with my code? Thanks!
var score = 0;
var people = 0;
var org = 0;
var focal = 0;
var location = 0;
var carry = 0;
//PEOPLE
if ($('input:radio:checked').val() === "Obama") {
people = -25;
}else if ($('input:radio:checked').val() === "Clinton"){
people = -15;
}else if($('input:radio:checked').val() === "Bush"){
people = 25;
}else if($('input:radio:checked').val() === "Romney"){
people = 0;
}else if($('input:radio:checked').val() === "Windsor"){
people = 25;
}else if($('input:radio:checked').val() === "Putin"){
people = -25;
};
//ORG
if ($('input:radio:checked').val() === "Christian") {
org = 20;
}else if ($('input:radio:checked').val() === "Boy Scouts"){
org = 10;
}else if($('input:radio:checked').val() === "Freemason"){
org = 30;
}else if($('input:radio:checked').val() === "KGB"){
org = -20;
}else if($('input:radio:checked').val() === "Islam"){
org = -30;
}else if($('input:radio:checked').val() === "Satanic Cult"){
org = -50;
};
//FOCAL
if ($('input:radio:checked').val() === "Financial") {
focal = 15;
}else if ($('input:radio:checked').val() === "Industry"){
focal = 20;
}else if($('input:radio:checked').val() === "Medical"){
focal = 5;
}else if($('input:radio:checked').val() === "Technology"){
focal = 30;
}else if($('input:radio:checked').val() === "War"){
focal = -30;
}else if($('input:radio:checked').val() === "Spy"){
focal = -20;
};
//LOCATION
if ($('input:radio:checked').val() === "United Kingdom") {
location = 5;
}else if ($('input:radio:checked').val() === "U.S.A."){
location = -15;
}else if($('input:radio:checked').val() === "China"){
location = 0;
}else if($('input:radio:checked').val() === "Germany"){
location = 20;
}else if($('input:radio:checked').val() === "Russia"){
location = -40;
}else if($('input:radio:checked').val() === "Mexico"){
location = -60;
};
//CARRY
if ($('input:radio:checked').val() === "Tune") {
var carry = 15;
}else if ($('input:radio:checked').val() === "Weight"){
var carry = 25;
}else if($('input:radio:checked').val() === "Stick"){
var carry = 0;
}else if($('input:radio:checked').val() === "Grudge"){
var carry = -25;
}else if($('input:radio:checked').val() === "Ebola"){
var carry = -80;
}else if($('input:radio:checked').val() === "Reset"){
var carry = -100;
};
var score = (people + org + focal + location + carry);
if(score>50){
$('.result').html('You Win!');
}else{
$('.result').html('You Lose!');
}
$('p').html("Your score is " + score + ".");
The problem is your radio selector, it will always return the very first checked radio value across all the groups instead of targeting specific groups.
The solution is to use the radio group name in the selector like $('input[name="people"]:radio:checked').val().
To add to that, you can simplify the code by using a value map like
var pmap = {
Obama: -25,
Clinton: -15,
Bush: 25,
Romney: 0,
Windsor: 25,
Putin: -25
};
var people = pmap[$('input[name="people"]:radio:checked').val()] || 0;
Create similar value maps for the other groups also.

Categories

Resources