I was wondering if i am doing my array sort correctly because I'm currently doing a leaderboard that will display the score from highest to lowest. The "temp 1-5" variable already has value's in them and i was wondering is there any mistake am i making.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
var name1;
var name2;
var name3;
var name4;
var name5;
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
var ask;
function main() {
start()
totalscore()
leaderboard()
}
function start() {
ask = prompt("How many people are playing")
if (ask == 3) {
name1 = prompt("What is the first player's name?")
name2 = prompt("What is the second player's name?")
name3 = prompt("What is the third player's name?")
number = 3
}
if (ask == 4) {
name1 = prompt("What is the first player's name?")
name2 = prompt("What is the second player's name?")
name3 = prompt("What is the third player's name?")
name4 = prompt("What is the forth player's name?")
number = 4
}
if (ask == 5) {
name1 = prompt("What is the first player's name?")
name2 = prompt("What is the second player's name?")
name3 = prompt("What is the third player's name?")
name4 = prompt("What is the forth player's name?")
name5 = prompt("What is the fifth player's name?")
number = 5
}
}
function randomnumber() {
var randomnumber;
randomnumber = Math.random() * 3;
return (Math.floor(randomnumber + 0.2));
}
function randomnumber1() {
var randomnumber1;
randomnumber1 = Math.random() * 3;
return (Math.floor(randomnumber1 + 0.2));
}
function randomnumber2() {
var randomnumber2;
randomnumber2 = Math.random() * 3;
return (Math.floor(randomnumber2 + 0.2));
}
function randomnumber3() {
var randomnumber3;
randomnumber3 = Math.random() * 3;
return (Math.floor(randomnumber3 + 0.2));
}
function randomnumber4() {
var randomnumber4;
randomnumber4 = Math.random() * 3;
return (Math.floor(randomnumber4 + 0.2));
}
function totalscore() {
var n;
var p;
var a;
var c;
var e;
var score = 0;
var score1 = 0;
var score2 = 0;
var score3 = 0;
var score4 = 0;
var total;
var total1;
var total2;
var total3;
var total4;
total = 0
total1 = 0
total2 = 0
total3 = 0
total4 = 0
for (n = 0; n < 10; n = n + 1) // to create total score//
{
number = randomnumber();
if (number == 0) {
score = score + 0;
} else if (number == 2) {
score = score + 2;
} else if (number == 3) {
score = score + 3;
}
total = total + score;
}
for (p = 0; p < 10; p = p + 1) // to create total score//
{
number1 = randomnumber1();
if (number1 == 0) {
score1 = score1 + 0;
} else if (number1 == 2) {
score1 = score1 + 2;
} else if (number1 == 3) {
score1 = score1 + 3;
}
total1 = total1 + score1;
}
for (a = 0; a < 10; a = a + 1) // to create total score//
{
number2 = randomnumber2();
if (number2 == 0) {
score2 = score2 + 0;
} else if (number2 == 2) {
score2 = score2 + 2;
} else if (number2 == 3) {
score2 = score2 + 3;
}
total2 = total2 + score2;
}
for (c = 0; c < 10; c = c + 1) // to create total score//
{
number3 = randomnumber3();
if (number3 == 0) {
score3 = score3 + 0;
} else if (number3 == 2) {
score3 = score3 + 2;
} else if (number3 == 3) {
score3 = score3 + 3;
}
total3 = total3 + score3;
}
for (e = 0; e < 10; e = e + 1) // to create total score//
{
number4 = randomnumber4();
if (number4 == 0) {
score4 = score4 + 0;
} else if (number4 == 2) {
score4 = score4 + 2;
} else if (number4 == 3) {
score4 = score4 + 3;
}
total4 = total4 + score4;
}
temp1 = total
temp2 = total1
temp3 = total2
temp4 = total3
temp5 = total4
}
function leaderboard() {
if (ask == 3) {
document.write("Player: " + name1 + " has a score of " + temp1 + "<br>")
document.write("Player: " + name2 + " has a score of " + temp2 + "<br>")
document.write("Player: " + name3 + " has a score of " + temp3 + "<BR>")
} else if (ask == 4) {
document.write("Player: " + name1 + " has a score of " + temp1 + "<br>")
document.write("Player: " + name2 + " has a score of " + temp2 + "<br>")
document.write("Player: " + name3 + " has a score of " + temp3 + "<BR>")
document.write("Player: " + name4 + " has a score of " + temp4 + "<BR>")
} else if (ask == 5) {
document.write("Player: " + name1 + " has a score of " + temp1 + "<br>")
document.write("Player: " + name2 + " has a score of " + temp2 + "<br>")
document.write("Player: " + name3 + " has a score of " + temp3 + "<BR>")
document.write("Player: " + name4 + " has a score of " + temp4 + "<BR>")
document.write("Player: " + name5 + " has a score of " + temp5 + "<BR>")
}
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function (a, b) {
return b - a
});
var myContent = '';
for (var d = 0; d < 5; d++) {
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
</BODY>
</HTML>
Related
I'd like to write a JavaScript program that displays a symmetric histogram like this image:
The program should ask the user to enter the number of bars to print and the character to use to draw the bars. The count of characters in the bar needs to be displayed on the right-side of each bar.
The example showed is when I entered # as the character and 13 as the number.
Here's my code:
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;
while (currentNum <= number) {
text += "<br>" + symbolNum + " " + currentNum;
symbolNum += symbol;
currentNum++;
}
document.write(text + "<br>");
And at last, I only can output the following:
I'd like to know what I can do in order to reverse the loop?
Try this
function SymmetricHistogram(){
const size = 10;
let numberX = 0;
let numberY = 0;
for(let i = size; i>=-size; i--) {
for(let j=size; j>=Math.abs(i); j--){
process.stdout.write("#");
}
numberX <=size ? console.log(numberX++) : console.log(--numberY);
}
}
SymmetricHistogram();
Or try the below
https://onecompiler.com/javascript/3x58bqr3h
Two different way for the same result. Not realy clean, but work.
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;
while (currentNum <= number) {
textTOP += "<br>" + symbolNum + " " + currentNum;
if (currentNum < number)
textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
symbolNum += symbol;
currentNum++;
}
document.write(textTOP + textBOTTOM + "<br>");
var symbol = '#';
var number = 13;
var currentNum = 1;
let text = "";
while (currentNum < number * 2) {
if (currentNum <= number) {
let num = currentNum;
text += "<br>" + symbol.repeat(num) + " " + num;
} else {
let num = Math.abs(number * 2 - currentNum);
text += "<br>" + symbol.repeat(num) + " " + num;
}
currentNum++;
}
document.write(text + "<br>");
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);
}
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;
}
}
}
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.
I'n new to programming and I tried something in JavaScript and it worked well in Chrome. But It fails to work in IE, Firefox, Safari and Opera. Am I doing anything wrong with my code?
function hp(form) {
var count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count10 = 0;
for (var i = 0; i < 3; i++) {
if (form.q1[i].checked == true) {
count1++;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q2[i].checked == true) {
count2++;
}
}
if (count2 !== 1) {
alert("Please Answer 2nd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q3[i].checked == true) {
count3++;
}
}
if (count3 !== 1) {
alert("Please Answer 3rd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q4[i].checked == true) {
count4++;
}
}
if (count4 !== 1) {
alert("Please Answer 4th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q5[i].checked == true) {
count5++;
}
}
if (count5 !== 1) {
alert("Please Answer 5th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q6[i].checked == true) {
count6++;
}
}
if (count6 !== 1) {
alert("Please Answer 6th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q7[i].checked == true) {
count7++;
}
}
if (count7 !== 1) {
alert("Please Answer 7th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q8[i].checked == true) {
count8++;
}
}
if (count8 !== 1) {
alert("Please Answer 8th Question");
return false;
}
for (var i = 0; i < 4; i++) {
if (form.q9[i].checked == true) {
count9++;
}
}
if (count9 !== 1) {
alert("Please Answer 9th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q10[i].checked == true) {
count10++;
}
}
if (count10 !== 1) {
alert("Please Answer 10th Question");
return false;
}
answer1 = (form.q1.value);
answer2 = (form.q2.value);
answer3 = (form.q3.value);
answer4 = (form.q4.value);
answer5 = (form.q5.value);
answer6 = (form.q6.value);
answer7 = (form.q7.value);
answer8 = (form.q8.value);
answer9 = (form.q9.value);
answer10 = (form.q10.value);
var a = parseInt(answer1);
var b = parseInt(answer2);
var c = parseInt(answer3);
var d = parseInt(answer4);
var e = parseInt(answer5);
var f = parseInt(answer6);
var g = parseInt(answer7);
var h = parseInt(answer8);
var ii = parseInt(answer9);
var j = parseInt(answer10);
var c = a + b + c + d + e + f + g + h + ii + j;
//document.getElementById("result").innerHTML= "The selected values are "+"</br>"+a+"</br>"+b+c+d+e+f+g+h+ii+j+"</br>"+c;
if (c <= 20) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 20) && (c <= 25)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 25) && (c <= 30)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 30) && (c <= 40)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 40) && (c <= 50)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 50) && (c <= 60)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 60) && (c <= 65)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 65) && (c <= 75)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 75) && (c <= 90)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
c = 0;
}
I tried this code in local host and i got my desired output in Google Chrome. When i tried the same page in Firefox and other browser, it failed to work. Only checkbox validation is working fine.
Thanks in Advance
From personal experience, I have noticed that Chrome is more forgiving when it comes to small errors. It is strange how you are not getting an error in the debug box at all...
But, a place I can see from reading the code is where you define the variables a,b,c... I recommend placing a comma after each. So, you get:
var a = parseInt(answer1),
b = parseInt(answer2),
c = parseInt(answer3),
d = parseInt(answer4),
e = parseInt(answer5),
f = parseInt(answer6),
g = parseInt(answer7),
h = parseInt(answer8),
ii = parseInt(answer9),
j = parseInt(answer10);
Then here is where I think you have an error. You have var c = ... again after already defining c. So, try removing the var right there.