Cannot call toFixed on a number variable - javascript

I am receiving the follow error in my Console :
" Uncaught TypeError: undefined is not a function "
<script>
//name : calculateResult()-->
function calculateResult() {
console.log("calculateResult() function called!");
//1. Declare Variables-->
var hoursWorked,
jobCategory,
jobCategorySelectedIndex,
hoursEligibleForBasePay,
hoursEligibleForOvertime,
basePayAmount,
overtimePayAmount,
totalPayAmount,
overtimePayRate;
//2. Values for Local Variables-->
hoursWorked = document.getElementById("txthoursWorked").value;
console.log("hoursWorked = " + hoursWorked);
//Get Select element choice: Job Category-->
jobCategorySelectedIndex = document.getElementById("seljobCategory").selectedIndex;
console.log("jobCategorySelectedIndex = " + jobCategorySelectedIndex);
jobCategory = document.getElementById("seljobCategory").options[jobCategorySelectedIndex].value;
console.log("jobCategory = " + jobCategory);
//3. Do Calculations-->
hoursWorked = parseFloat(hoursWorked);
if (jobCategory == "M") {
basePayRate = "25";
} else if (jobCategory == "R") {
basePayRate = "20";
} else if (jobCategory == "S") {
basePayRate = "15";
}
hoursEligibleForBasePay = 40;
basePayAmount = basePayRate * hoursEligibleForBasePay;
console.log("basePayAmount = " + basePayAmount);
console.log("hoursEligibleForOvertime =" + hoursEligibleForBasePay);
if (hoursWorked > 40) {
hoursEligibleForOvertime = hoursWorked - 40;
} else {
hoursEligibleForOvertime = 0;
}
console.log("hoursEligibleForOvertime = " + hoursEligibleForOvertime);
overtimePayRate = 1.5 * basePayRate;
overtimePayAmount = overtimePayRate * hoursEligibleForOvertime;
totalPayAmount = basePayRate + overtimePayAmount;
console.log("overtimePayRate = " + overtimePayRate);
console.log("overtimePayAmount = " + overtimePayAmount);
console.log("totalPayAmount = " + totalPayAmount);
//4. Display Results-->
displayString = "Base Pay " + "$" + basePayAmount.toFixed(2) + "<br />" +
"Overtime Pay " + "$" + overtimePayAmount.toFixed(2) + "<br />"
"Total Pay " + "$" + totalPayAmount.toFixed(2);
document.getElementById("divDisplay").innerHTML = displayString;
}
</script>
the error is in the display string on the Total PayAmount line
any ideas?

The actual error is not actually on that line.
totalPayAmount is defined here:
totalPayAmount = basePayRate + overtimePayAmount;
basePayRate is defined here:
if (jobCategory == "M") {
basePayRate = "25";
} else if (jobCategory == "R") {
basePayRate = "20";
} else if (jobCategory == "S") {
basePayRate = "15";
}
So basePayRate is a string. Then totalPayAmount is also a string, which would not have a toFixed method.

Related

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

Trying to grab a innerhtml from within a innerhtml

So i've recently ran into issues with trying to move specific pieces of a <p> </p> called result. as such i thought hey! wouldn't be easier to break each part inside of result down into another <p>!? well it works lol however trying to grab that inner <p> that in this cause we'll call vault is being difficult. I've tried several methods but cant seem to grab it's value from outside in a document.getElementByID....here's the code below for the html.
document.getElementById("result").innerHTML = Monster + "<p id='vault'> || HP: " + HP + "</p> || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
then the script that eventually calls it
function Combat(id){
document.getElementById("vault").innerHTML = id;
document.getElementById("C").value = id
}
So what i'm trying is change id "C" to ID"VAULT" inside of id ("result").
any ideas on why i can't grab vault?
What you want would be easier with Object-oriented JavaScript.
Usually when coding JavaScript you want to be as independent of the DOM (HTML) as possible.
Consider the following example:
/**
* Monster
*/
var Monster = (function() {
function Monster(HP, DEF, ATK, DB, RET, INT, MEXP) {
if (HP === void 0) {
HP = 100;
}
if (DEF === void 0) {
DEF = 10;
}
if (ATK === void 0) {
ATK = 100;
}
if (DB === void 0) {
DB = 10;
}
if (RET === void 0) {
RET = true;
}
if (INT === void 0) {
INT = 100;
}
if (MEXP === void 0) {
MEXP = 100;
}
this.HP = HP;
this.DEF = DEF;
this.ATK = ATK;
this.DB = DB;
this.RET = RET;
this.INT = INT;
this.MEXP = MEXP;
}
/**
* getHTML
*/
Monster.prototype.getHTML = function() {
return "HP: " + this.HP + " || Defense: " + this.DEF + " || Attack: " + this.ATK + " || Can it Dodge/Block: " + this.DB + " || Can it retaliate: " + this.RET + " || Initative: " + this.INT + " || Exp: " + this.MEXP;
};
/**
* attacked
*/
Monster.prototype.attacked = function(damage) {
if (damage === void 0) {
damage = 0;
}
//check defences
if (damage > this.DEF + this.DB) {
//take damage
this.HP -= (damage - this.DEF + this.DB);
}
if (this.HP < 0) {
//Return true if it slew the monster
return true;
} else {
//Return false if the monster survived
return false;
}
};
return Monster;
}());
/**
* Area
*/
var Area = (function() {
function Area(name) {
if (name === void 0) {
name = "Vault";
}
this.name = name;
this.monsters = [];
}
/**
* addMonster
*/
Area.prototype.addMonster = function(monster) {
this.monsters.push(monster);
return this;
};
/**
* attackVault
*/
Area.prototype.assault = function(damage) {
if (damage === void 0) {
damage = 0;
}
//If no monster
if (this.monsters.length < 1) {
alert("You have cleared this vault");
return true;
} else {
//If monsters exists, attack the first
var monsterKilled = this.monsters[0].attacked(damage);
//If the monster was killed
if (monsterKilled) {
//remove monster
this.monsters.splice(0, 1);
//Alert the player
alert("Well done hero!\nOnly " + (this.monsters.length) + " remaining!");
}
}
//Return maybe monsters left?
return this.monsters.length < 1;
};
return Area;
}());
////GRAP HTML ELEMENT
var output = document.getElementById("current-monster");
////RUNNING YOUR GAME
//Build and populate world
var vault = new Area();
vault
.addMonster(new Monster())
.addMonster(new Monster());
//INTERACTION
alert("Start");
//Hit the vault till it is empty
while (vault.assault(45) != true) {
output.innerHTML = vault.monsters[0].getHTML();
alert("Attack!");
}
output.innerHTML = "Victory!";
<h1 id="title">Monster Game!</h1>
<h2 id="current-monster"></h2>
See how i can easily access the data though JavaScript?
When coding a JavaScript game, it makes sense to keep important data and structures in your JavaScript.
Ok so i added the bit - ADyson suggested...
document.getElementById("result").innerHTML = Monster + "<p id='vault(" + loop + ")'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
}
}
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
var id = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = id;
submit();
}
However now when i run it on the " ).innerHTML;" i'm getting a
MonsterGen.html:426 Uncaught TypeError: Cannot read property
'innerHTML' of nullCombat # MonsterGen.html:426onclick #
MonsterGen.html:1
Ok I found out exactly was was going wrong; it was the naming convention in the <P>.
Originally it was id='vault(" + loop + ")'... this would make it vault(1) etc.... however the getElement was getting it by this call ("vault" + id) so it would call vault1....thus two separate id's entirely....that's why it was returning null.
So I removed the () in the equation and now everything is working beautifully.

Javascript function logic

I have 3 js functions passing into each other for a blackjack game,
Hit() - Which gets a new card
checkCard() - which checks the card isnt in the users hand already
userTotal () - totals the value of the card and displays it in the DOM
The same card can appear more than once. the major flaw is with checking the card against others in an array of userCards
My logic is wrong. Could someone help me?
function hit() {
var cards = 2;
userIndex++;
var rankSelect = Math.floor(Math.random() * 13);
var suitSelect = Math.floor(Math.random() * 4);
var card = (rank[rankSelect] + suit[suitSelect]);
checkCard(card);
}
function checkCard(card) {
//if card = card in used array, select new card
for (i=0;i<=userCards.length;i++){
if (card = userCards[i] ) {
//selectCards(card)
var newRank = Math.floor(Math.random()*13);
var newSuit = Math.floor(Math.random()*4);
var newCard = (rank[newRank] + suit[newSuit]);
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src="+"includes/images/cards/"+ newCard + ".png >"
userCards[userCards.length] = newCard;
userTotal();
} else {
userCards[userIndex] = card;
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src="+"includes/images/cards/"+ card + ".png >"
userTotal();
}
}
}
function userTotal(userTotal){
var userTotal = 0;
for (i=0;i<userCards.length;i++){
var value = userCards[i];
if(userCards[i].charAt(0) == "a"){
value = parseInt((prompt("ACE, 1 or 11?")));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "k" || userCards[i].charAt(0) == "q" || userCards[i].charAt(0) == "j"){
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}else if (userCards[i].charAt(0) == "1" || userCards[i].charAt(1) == "0"){
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else {
value = parseInt(userCards[i].charAt(0));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}
if (userTotal > 21){
document.getElementById("userTotal").innerHTML = "Bust";
//document.getElementById("hit").disabled = true;
}
}
}
When you are inside 'checkCard' and if you get a card already in hand then you are again fetching a random card but this time you are not checking whether its already in hand or not.
You need to keep checking card until you won't get a fresh one.
replace this line :
var newCard = (rank[newRank] + suit[newSuit]);
with
card = (rank[newRank] + suit[newSuit]);
checkCard(card);
Try below :
function hit() {
var cards = 2;
userIndex++;
var rankSelect = Math.floor(Math.random() * 13);
var suitSelect = Math.floor(Math.random() * 4);
var card = (rank[rankSelect] + suit[suitSelect]);
checkCard(card);
}
function checkCard(card) {
//if card = card in used array, select new card
for (i = 0; i <= userCards.length; i++) {
if (card = userCards[i]) {
//selectCards(card)
var newRank = Math.floor(Math.random() * 13);
var newSuit = Math.floor(Math.random() * 4);
card = (rank[newRank] + suit[newSuit]);
chekCard(card);
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src=" + "includes/images/cards/" + card + ".png >"
userCards[userCards.length] = card;
userTotal();
} else {
userCards[userIndex] = card;
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src=" + "includes/images/cards/" + card + ".png >"
userTotal();
}
}
}
function userTotal(userTotal) {
var userTotal = 0;
for (i = 0; i < userCards.length; i++) {
var value = userCards[i];
if (userCards[i].charAt(0) == "a") {
value = parseInt((prompt("ACE, 1 or 11?")));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "k" || userCards[i].charAt(0) == "q" || userCards[i].charAt(0) == "j") {
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "1" || userCards[i].charAt(1) == "0") {
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else {
value = parseInt(userCards[i].charAt(0));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}
if (userTotal > 21) {
document.getElementById("userTotal").innerHTML = "Bust";
//document.getElementById("hit").disabled = true;
}
}
}

else part of if statement not executing

This JavaScript code I have been working on works for the most part but I keep running into quirks. I worked around the others as you can see in the comments, but I cannot get the part near the bottom to execute. It is the if (isCorrect != "Yes")
line. I had it as an if/else, but the else would never execute. So I made it a separate if statement
function inputNum() {
/* initialize variables */
var inGuess = "";
var spaceChar = " ";
var loopCt;
var guessResult = "";
var correctNum;
var correctNum = getRandomInt(1, 100);
var guessNum = 0;
var guessLeft = 10;
var guessMsg = ""
var isCorrect = "No";
/* added the following so that when they try the game again it resets the results */
document.getElementById("fireworks").src = "images/Question_mark.png";
resetTable();
for (loopCt = 1; loopCt < 11; loopCt++) {
inGuess = prompt("Please enter your guess(enter -1 to exit) Do not press Enter", "0");
if (inGuess == "-1") {
break;
}
if (inGuess == null || inGuess == "") {
alert("Blanks are not allowed. To exit enter '-1'.");
} else {
guessNum = parseInt(inGuess, 10);
guessMsg = ", you have " + --guessLeft + " guesses left";
if (inGuess == correctNum) {
guessResult = "Correct!";
isCorrect = "Yes";
document.getElementById('emp' + loopCt).innerHTML = guessResult;
document.getElementById('ct' + loopCt).innerHTML = inGuess;
alert("Congratulations, you guess correctly!");
break;
} else if (guessNum < 1 || guessNum > 100) {
alert("You must choose a number between 1 and 100");
} else if (guessNum < correctNum) {
guessResult = "Too low";
} else {
guessResult = "Too high";
}
document.getElementById('emp' + loopCt).innerHTML = guessResult + guessMsg;
document.getElementById('ct' + loopCt).innerHTML = inGuess;
}
}
if (isCorrect == "Yes") {
document.getElementById("fireworks").src = "images/fireworks.jpg";
}
/* for some reason the else is not being picked up so I have to change it to another if statement
else
*/
if (isCorrect != "Yes") {
var errMsg = "The correct number was " + correctNum;
errMsg = errMsg + " Please try again.";
document.getElementById(guessResult).innerHTML = errMsg;
/* the line above this does not appear to function, don't know why so I am adding the line below*/
document.getElementById("fireworks").src = "images/wrong.png";
alert(errMsg);
}
}
/* random number function */
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/* clear the results table */
function resetTable() {
/* the code below kept getting the error TypeError: document.getElementById(...) is null even though
I tried it with the code above that works so I have to do it brute force method
for (i = 1;i<11;i++)
{
document.getElementById('emp'+i).innerHTML=" ";
document.getElementById('ct'+i).innerHTML=" ";
}
*/
document.getElementById('emp1').innerHTML = " ";
document.getElementById('ct1').innerHTML = " ";
document.getElementById('emp2').innerHTML = " ";
document.getElementById('ct2').innerHTML = " ";
document.getElementById('emp3').innerHTML = " ";
document.getElementById('ct3').innerHTML = " ";
document.getElementById('emp4').innerHTML = " ";
document.getElementById('ct4').innerHTML = " ";
document.getElementById('emp5').innerHTML = " ";
document.getElementById('ct5').innerHTML = " ";
document.getElementById('emp6').innerHTML = " ";
document.getElementById('ct6').innerHTML = " ";
document.getElementById('emp7').innerHTML = " ";
document.getElementById('ct7').innerHTML = " ";
document.getElementById('emp8').innerHTML = " ";
document.getElementById('ct8').innerHTML = " ";
document.getElementById('emp9').innerHTML = " ";
document.getElementById('ct9').innerHTML = " ";
}

I can't figure out how to write this "if statement"

I need to have only the multiple gifts outputted by the names of people that gave the gift.
example: multiple toasters by: jack and jill
heres my code: thanks for the help. My loop works but not my ending if statement. confused...
<script type="text/javascript">
var guest = "yes"
var gift, side, yourName, kind, groomNameAccum, brideNameAccum;
var toaster, silverware, stemware, giftType;
var noGift = 0;
var groomCounter = 0;
var brideCounter = 0;
kind = parseInt(kind);
//initalizing loop
weddingGift = "yes"
//start loop
while (guest == "yes") {
side = prompt("Which side are you on? groom or bride?", "")
yourName = prompt("Whats your name?", "");
kind = prompt("What kind of gift?", "");
if (side == "groom") {
groomCounter = groomCounter + 1;
if (groomCounter == 1) {
groomNameAccum = "Groom side: <br>" + groomCounter + ". " + yourName + ": " + kind;
} else {
groomNameAccum = groomNameAccum + "<br>" + groomCounter + ". " + yourName + ": " + kind;
}
} else
if (side == "bride") {
brideCounter = brideCounter + 1;
if (brideCounter == 1) {
brideNameAccum = "<p>Bride side: <br>" + brideCounter + ". " + yourName + ": " + kind;
} else {
brideNameAccum = brideNameAccum + "<br>" + brideCounter + ". " + yourName + ": " + kind;
}
}
if (kind > 1) {
giftType = toaster + silverware + stemware;
} else {
giftType = noGift;
}
guest = prompt("Are there anymore guests?", "yes");
}
document.write(groomNameAccum);
document.write(brideNameAccum);
document.write("<p>Multiples Toasters by:<br>" + giftType + yourName + "<br/>");
document.write("Multiples Silverware by:<br>" + gift + "<br/>");
document.write("Multiples Stemware by:<br>" + gift);
// -->
</script>
If kind should be an integer then there should be parseInt before if (kind > 1) {
kind = parseInt(kind);
if (kind > 1) {
giftType = toaster + silverware + stemware;
} else {
giftType = noGift;
}
Or simply
kind = parseInt(prompt("What kind of gift?", ""));
Because promt returns a string or null.
Here in the popup for "What kind of gift?" we are entering some text for that. If you are doing parseInt(kind) but its value is text only. So in java script you are not able do any operation between two different types like (int and text). So the last if condition for if(kind > 1) is not executing.
Demo

Categories

Resources