Add Variables In If Statement From Values Determined by Radio Buttons - javascript

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.

Related

Am i missing (not covering) any cases in this code (JavaScript)?

function Scholarship(input){
let income = input.shift();
let avgGrade = input.shift();
let minSalary = input.shift();
let isExcellent = false;
let isSocial = false;
let socialSch = 0 ;
let excellentSch = 0 ;
if (avgGrade >= 5.50) {
isExcellent = true;
excellentSch = avgGrade * 25;
}
if (income <= minSalary && avgGrade >= 4.50) {
isSocial = true;
socialSch = minSalary * 0.35;
}
if ((isSocial == false) && (isExcellent == false)){
console.log("You cannot get a scholarship!");
} else if (excellentSch >= socialSch){
console.log(`You get a scholarship for excellent results ${Math.floor(excellentSch)} BGN`);
} else if (socialSch > excellentSch){
console.log(`You get a Social scholarship ${Math.floor(socialSch)} BGN`);
}
}
Scholarship([number, number, number]);
All input numbers(data) are positive.
There should be a mistake somewhere in my logic!
Maybe i am missing to check for some other cases.

JavaScript While Loop Variable Returning NaN

I'm making a Numerology conversion web app with JavaScript and HTML5. I've ran into a strange issue with a variable and loops. Below is my whole project in its current form.
<html>
<body>
<h1>My First Numerology Project</h1>
<form>
Month:<br>
<input type="text" maxlength="2" name="userInputMonth" id='userInputMonth'>
<br>
Day:<br>
<input type="text" maxlength="2" name="userInputDay" id='userInputDay'>
<br>
Year:<br>
<input type="text" maxlength="4" name="userInputYear" id='userInputYear'>
<br><br>
First Name:<br>
<input type="text" name="userInputFirstName" id='userInputFirstName'>
<br>
Middle Name:<br>
<input type="text" name="userInputMiddleName" id='userInputMiddleName'>
<br>
Last Name:<br>
<input type="text" name="userInputLastName" id='userInputLastName'>
<br><br>
<input type="button" value="Calculate" name="Calculate" onclick="BirthDayCalculation()"/>
</form>
<p id="LLNResult"></p>
<br>
<p id="OPNResult"></p>
<br>
<p id="SNResult"></p>
<br>
<p id="PODNResult"></p>
<script type="text/javascript">
//Defined var
var LLNTemp1;
var LLNTemp2;
var LLNReduce1;
var LLNReduce2;
var NameTemp1;
var NameTemp2;
var OPNReduce1;
var OPNReduce2;
var SNReduce1;
var SNReduce2;
var PODNReduce1;
var PODNReduce2;
function BirthDayCalculation() {
var Reduction1 = 0;
var LLNReduceFinal2 = 0;
var Day = document.getElementById('userInputDay').value;
var Month = document.getElementById('userInputMonth').value;
var Year = document.getElementById('userInputYear').value;
var FirstName = document.getElementById('userInputFirstName').value;
var MiddleName = document.getElementById('userInputMiddleName').value;
var LastName = document.getElementById('userInputLastName').value;
var LLN = ("" + Day + Month + Year).toString();
var FullName = ("" + FirstName + MiddleName + LastName).toString().toUpperCase();
var FullNameLength = parseInt(FullName.length);
var LLNLength = parseInt(("" + Day + Month + Year).length);
var i = 0;
var LLNTemp2 = 0;
while (i < LLNLength) {
LLNTemp1 = parseInt(LLN.charAt(i));
LLNTemp2 += LLNTemp1;
i++;
}
if (LLNTemp2 > 9) {
var i = 0;
var a = parseInt(LLNTemp2.toString().length);
var LLNReduceFinal1 = 0;
var LLNTemp3String = LLNTemp2.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal1 += LLNReduce1;
i++;
}
var LLNReduceFinal2 = 0;
var Reduction1 = LLNReduceFinal1;
if (LLNReduceFinal1 > 9) {
var i = 0;
var a = parseInt(Reduction1.toString().length);
var LLNTemp3String = Reduction1.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal2 += LLNReduce1;
i++;
}
}
}
var OPN = 0;
var SN = 0;
var PODN = 0;
var PODNWhole = 0;
var i = 0;
while (i < FullNameLength) {
NameTemp1 = FullName.charAt(i);
var OPNTemp = 0;
var SNTemp = 0;
if (NameTemp1 == "A") SNTemp = 1;
if (NameTemp1 == "J" || NameTemp1 == "S") OPNTemp = 1;
if (NameTemp1 == "B" || NameTemp1 == "K" || NameTemp1 == "T") OPNTemp = 2;
if (NameTemp1 == "C" || NameTemp1 == "L") OPNTemp = 3;
if (NameTemp1 == "U") SNTemp = 3;
if (NameTemp1 == "D" || NameTemp1 == "M" || NameTemp1 == "V") OPNTemp = 4;
if (NameTemp1 == "E") SNTemp = 5;
if (NameTemp1 == "N" || NameTemp1 == "W") OPNTemp = 5;
if (NameTemp1 == "F" || NameTemp1 == "X") OPNTemp = 6;
if (NameTemp1 == "O") SNTemp = 6;
if (NameTemp1 == "G" || NameTemp1 == "P" || NameTemp1 == "Y") OPNTemp = 7;
if (NameTemp1 == "H" || NameTemp1 == "Q" || NameTemp1 == "Z") OPNTemp = 8;
if (NameTemp1 == "I") SNTemp = 9;
if (NameTemp1 == "R") OPNTemp =9;
OPN += OPNTemp;
SN += SNTemp;
PODNWhole += SNTemp;
PODNWhole += OPNTemp;
i++;
}
var PODN = PODNWhole
var OPNReduceFinal = 0;
if (OPN > 9) {
var OPNLength = parseInt(OPN.toString().length);
var OPNTempString = OPN.toString();
var i = 0;
while (i < OPNLength) {
OPNReduce1 = parseInt(OPNTempString.charAt(i));
OPNReduceFinal += OPNReduce1;
i++;
}
}
var SNReduceFinal = 0;
if (SN > 9) {
var SNLength = parseInt(SN.toString().length);
var SNTempString = SN.toString();
var i = 0;
while (i < SNLength) {
SNReduce1 = parseInt(SNTempString.charAt(i));
SNReduceFinal += SNReduce1;
i++;
}
}
var PODNReduceFinal = 0;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
// var PODNReduceFinal = PODNReduce2;
// var PODN = PODNReduce2;
}
var LLNResult = "Your Life Lesson Number Is:" + LLNTemp2 + "/" + Reduction1;
if (LLNReduceFinal2 != 0) {
LLNResult = LLNResult + "/" + LLNReduceFinal2;
}
var OPNResult = "Your Outer Personality Number is:" + OPN;
if (OPNReduceFinal != 0) {
var OPNResult = OPNResult + "/" + OPNReduceFinal;
}
var SNResult = "Your Soul Number is:" + SN;
if (SNReduceFinal != 0) {
var SNResult = SNResult + "/" + SNReduceFinal;
}
var PODNResult = "Your Path of Destiny Number is:" + PODNWhole;
if (PODNReduceFinal != 0) {
var PODNResult = PODNResult + "/" + PODNReduceFinal;
}
if (LLNTemp2 != 0) {
document.getElementById("LLNResult").innerHTML = LLNResult;
}
if (PODNWhole != 0) {
document.getElementById("OPNResult").innerHTML = OPNResult;
document.getElementById("SNResult").innerHTML = SNResult;
document.getElementById("PODNResult").innerHTML = PODNResult;
}
}
</script>
</body>
</html>
So basically you enter your birthday and full name into a form. the script will then convert the name to numbers A = 1, B = 2.... and reduce both to single digits. the numbers will be added one by one. example. 13=4, 55=10, 63=9.
Here is the general code used to make reductions. Let's make PODN = 55
var PODNReduceFinal = 0;
var PODN = 55;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
}
Currently, it only loops once but I would like to have it get reduced to the lowest number possible. 1 in this case. I was thinking that if I change the if to a while it would accomplish this but it doesn't work the way I thought it would. I tried to make some changes and got stuck in a loop. So I started to troubleshoot. I added another variable to prevent the whole loop from looping infinitely.
var PODNReduceFinal = 0;
var PODN = 55;
while (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduce2 += PODNReduce1;
i++;
}
var PODNReduceFinal = PODNReduce2;
var PODN = PODNReduce2;
}
Using this I thought when PODN would be checked by the while loop first it would run through the first steps. Get the length of the number, in this case 2. Convert it to a string so it can pull the digits one by one. Pull the digits in sequence with the length of the loop and convert them to numbers. Add them together in PODNReduce2, 55=10. Set PODNReduceFinal = 10, set PODN = 10. Then return to the first condition and check that PODN is now 10 and is greater than 9. Loop again to reduce further. Doing this until it's a single digit stored in PODNReduceFinal. But that's not what happens. When I try to display PODNReduceFinal I get NaN. Even if I revert the first "while" to "if" it still doesn't work. I'm at a loss. Please help.

Number concatenates instead of being added

Everything works fine on my code until I enter a value for shipping it concatenates to the result instead of addition.
function subtotal(){
var a,b = 0;
var row = $('#tbody tr').not(':first-child').length;
for(i=0;i <= row;i++){
a = parseFloat($('#i-total'+i).val());
b += a;
}
$('#sub-total').val(parseFloat(Math.round(b * 100) / 100).toFixed(2));
$('#sub-total').attr('value',parseFloat(Math.round(b * 100) / 100).toFixed(2));
var dis = $('#disc-val').val();
$('#disc-val').attr('value',dis);
var tax = $('#tax').val();
$('#tax').attr('value',tax);
if(tax == '' || dis == ''){
tax = 0;
tax = parseFloat(tax);
dis = 0;
dis = parseFloat(dis);
}
var stat1 = $('#disc-val').attr('data-stat');
if(stat1 === 'on'){
b = b-(b*dis/100);
// console.log('disc%'+z);
}
else if(stat1 === 'off'){
b = b - dis;
// console.log('disc'+y);
}
var stat2 = $('#tax').attr('data-stat');
if(stat2 === 'on'){
b = (b*tax/100)+b;
}
else if(stat2 === 'off'){
b = b + tax;
}
var ship = $('#shipping-val').val();
$('#shipping-val').attr('value',ship);
if(ship == ''){
ship = 0;
ship = parseFloat(ship);
}
b = (ship + b);
$('#whole-total').attr('value', b);
}
try to use below way
if(ship == ''){
ship = 0;
ship = parseFloat(ship);
}
b = parseFloat(ship) + parseFloat(b);
The variable ship is a string if it's not empty.
Should this
if(ship == ''){
ship = 0;
ship = parseFloat(ship);
}
be
if(ship == ''){
ship = 0;
} else {
ship = parseFloat(ship);
}
Ship value is mishandled here :
var ship = $('#shipping-val').val();
$('#shipping-val').attr('value',ship);
if(ship == ''){
ship = 0;
ship = parseFloat(ship);
}
if(ship == ''){
ship = 0;
}
else{
ship = parseFloat(ship);
}
or it can be as
var ship = $('#shipping-val').val();
$('#shipping-val').attr('value',ship);
if(ship == ''){
ship = 0;
}
var ship = $('#shipping-val').val();
$('#shipping-val').attr('value',ship);
if(ship == ''){
ship = 0;
}
ship = parseFloat(ship); // out of conditional statement

Contribution margin percentage

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

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Categories

Resources