Javascript If statement not acknowledged - javascript

Here is the code
setHighScore: function() {
var highScore = 0;
if (!window.snake || !window.fpsls || !window.fmlts) {
return;
}
if (++bot.tickCounter >= 20) {
bot.tickCounter = 0;
var currentScore = parseInt(Math.floor(150 * (window.fpsls[window.snake.sct] +
window.snake.fam / window.fmlts[window.snake.sct] - 1) - 50) / 10);
if (Number(currentScore) > Number(highScore)) {
highScore = currentScore;
window.localStorage.setItem('highScoreLoc', highScore);
console.log('Current Score: ' + currentScore);
}
}
},
onFrameUpdate: function() {
// Botstatus overlay
var generalStyle = '<span style = "opacity: 0.35";>';
window.fps_overlay.innerHTML = generalStyle + 'FPS: ' +
userInterface.framesPerSecond.getFPS() + '</span>';
if (window.position_overlay && window.playing) {
// Display Personal High Score
userInterface.setHighScore();
window.scoreHuD.innerHTML = generalStyle +
'Your High Score: ' + parseInt(Number(window.localStorage.getItem('highScoreLoc')));
// Display the X and Y of the snake
window.position_overlay.innerHTML = generalStyle +
'X: ' + (Math.round(window.snake.xx) || 0) +
' Y: ' + (Math.round(window.snake.yy) || 0) +
'</span>';
}
It's meant to check if the score is bigger than the high score then save the new high score (if its bigger) and after that print it on screen. But it isn't for some reason
line 10 is the if statement
the 2 lines above it are to find the current score and i know it outputs the current score because of line 13
Its Tampermonkey
and the actual script https://github.com/Classicanon/Slither.io-bot/blob/master/bot.user.js For (Slither.io)

Related

Array element mysteriously overwritten

I'm learning p5.js.
I have a function that is called in setup() (don't worry, just the call is in setup, it is defined elsewhere):
CreateMaze = () => {
for(let i = 1; i <= numTiles; i++) {
let newTile = CreateTile(i);
let tileAdded = false;
while(!tileAdded) {
for(let j = 0; j < tiles.length; j++) {
print('new tile ' + newTile.x + ' ' + newTile.y);
print('array tile ' + tiles[j].x + ' ' + tiles[j].y);
if(newTile.x == tiles[j].x && newTile.y == tiles[j].y) {
print('new tile ' + newTile.x + ' ' + newTile.y);
print('array tile ' + tiles[j].x + ' ' + tiles[j].y);
newTile = CreateTile(i);
} else {
tiles.push(newTile);
tileAdded = true;
}
}
}
}
}
Also in setup(), I create a tile with let centralTile = new Tile(floor(windowWidth/2), floor(windowHeight/2),'#4caf50'); and push it to an array by tiles.push(centralTile);.
CreateTile is:
CreateTile = (ndx) => {
print('creating tile; index: ' + ndx);
let dir = ChooseDir(); //choose a direction
print(dir);
let xoff, yoff;
switch(dir) { //assign an offset value
case "N": xoff = 0; yoff = -50; break;
case "E": xoff = 50; yoff = 0; break;
case "S": xoff = 0; yoff = 50; break;
case "W": xoff = -50; yoff = 0; break;
}
//create a tile based on previous tile's location
let newTile = new Tile(tiles[ndx - 1].x + xoff, tiles[ndx - 1].y + yoff);
print('new tile ' + newTile.x + ' ' + newTile.y);
print('array tile (' + ndx-1 + ') ' + tiles[ndx-1].x + ' ' + tiles[ndx-1].y);
return newTile;
}
I'm running into an issue where the first tile I created in setup is the same as the second that comes from CreateTile(). I used the print statements to see where the value for the first tile is changing. It is right before the if. After I create the second tile, the prints tell me the two are different. But just before I compare them, they are the same. I cannot figure out why/how I'm changing the values of this initial array item. There is nothing I can find that would suggest it's changing. Like I said, when I create a second tile, it is different from the first (like it should be). But when it comes time to compare, they are the same. Where is this change occurring?

How can I make an if else statement in JavaScript prompt a user to hit a button to continue the statement?

I have built a little project game and there is a combat system. The problem is if you hit attack it runs the if else statement all the way through but doesn't show everything. It also gives me a Not a Number error if you lose, and I can't figure out what to do. Do I need to change the order of statements or something like that?
setFightEvent: function() {
let getArena = document.querySelector(".arena");
let getEnemy = document.querySelector(".enemy");
let enemy00 = new Enemy("Goblin", 100, 0, 20, 50, 100, 100);
let enemy01 = new Enemy("Troll", 200, 0, 40, 50, 80, 150);
let chooseRandomEnemy= Math.floor(Math.random() * Math.floor(2));
switch (chooseRandomEnemy) {
case 0:
enemy = enemy00;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
case 1:
enemy = enemy01;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
}
getEnemy.innerHTML = '<img src="img/avatar-enemy/' + enemy.enemyType.toLowerCase() + '.jpg" alt="' + enemy.enemyType + '" class="img-enemy"><div><h3 class="type-enemy">' + enemy.enemyType + '</h3><p class="health-enemy">Health: ' + enemy.health + '</p><p class="mana-enemy">Mana: ' + enemy.mana + '</P><p class="dexterity-enemy>Dexterity :' + enemy.dexterity + '</p></div>';
},
FightEvent: function() {
let getEnemy = document.querySelector(".enemy");
getEnemy.style.visibility = 'visible';
let getArena = document.querySelector(".arena");
let getPlayerHealth = document.querySelector(".health-player");
let getEnemyHealth = document.querySelector(".health-enemy");
let getPlayerGold = document.querySelector(".gold-player");
let getPlayerDexterity = player.dexterity;
let getEnemyDexterity = enemy.dexterity;
let playerAttack = function () {
let calcBaseDamage;
if (player.mana > 0) {
calcBaseDamage = player.strength * player.mana / 1000;
} else {
calcBaseDamage = player.strength * player.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(10));
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random() * Math.floor(player.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
let enemyAttack = function () {
let calcBaseDamage;
if (enemy.mana > 0) {
calcBaseDamage = enemy.strength * enemy.mana / 1000;
} else {
calcBaseDamage = enemy.strength * enemy.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(6))
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random * Math.floor(enemy.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
if (getPlayerDexterity >= getEnemyDexterity) {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
} else {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + ' hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
getPlayerHealth.innerHTML = 'Health: ' + player.health;
}
}
} else if (getEnemyDexterity >= getPlayerDexterity) {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + 'hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
alert("Select another action before fighting again!");
} else {
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
}
}
}
},
the code seems to run fine unless you are going to lose, then it just breaks. I want to be able to say the first if else, then ask the user to hit a button before it continues. Like, if you don't kill them in one hit I would like it to show the updated health of the player and monster THEN run the if else statement again. I think the problem is if you dont OTK them it just dies. I hope that makes sense!
ps. https://squarecylinder.github.io/Stress-of-The-Kingdom/ here is a link to the game, but I used absolute positioning in CSS to line everything up, so I don't think it would look right in every display! I'm trying to figure that out as well!
The comments have already addressed the fact that you're stating Math.random instead of calling Math.random() at one point in your code, so I'll leave that alone. Other than that, this line doesn't have a semicolon at the end:
getArena.innerHTML = '<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
It occurs twice in the code. I haven't set up a running sample of the code, so I don't know if this is your only remaining issue. If it still doesn't work after making this update, let me know and I'll remove this answer.
Side note:
Your random statements are a little bit needlessly complex. For example, with this line:
Math.floor(Math.random() * Math.floor(10))
there's no need to floor 10. 10 is already a flat integer. In fact, because you're using a lot of randomness, I'd use randojs.com to make all your randomness simpler and more readable. The line above can be written as just rando(0, 9). If you choose to use randojs, all you have to do is add the following line to the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>

JS Changing Classes issue

I'm using API sockets to update the market data.
and I want to classes change when the price goes up and down,
my first class (_class) is working successfully,
second class (_class2) is working at the start by changing to UP (pump) but it won't get back to down (dump) when the price goes down just like the first class. I'm in a bit of confusion coz I'm not so experienced at js.
can anyone tell me where I am mistaken?
window.updateMarkets = function (data) {
if (data.coin != undefined) {
var coin = 'BTC_' + data.coin;
var coin_data = data.msg;
var _coinTable = $('#coins-info-table');
var row = _coinTable.find("tr#" + coin);
price = _coinTable.find("tr#" + coin + " .price");
change = _coinTable.find("tr#" + coin + " .change");
volume = _coinTable.find("tr#" + coin + " .volume");
capital = _coinTable.find("tr#" + coin + " .market_capital");
supply = _coinTable.find("tr#" + coin + " .supply");
_price = formatter.format(coin_data.price);
previous_price = $(price).data('usd');
_class = coin_data.cap24hrChange >= 0 ? 'increment' : 'decrement';
_class2 = coin_data.cap24hrChange >= 0 ? 'pump' :'dump';
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
}
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
}
$(volume).html(formatter.format(coin_data.volume));
$(capital).html(formatter.format(coin_data.mktcap));
$(supply).html(coin_data.supply);
if (_price !== previous_price) {
_class = previous_price < _price ? 'increment' : 'decrement';
_class2 = previous_price < _price ? 'pump' : 'dump';
$(row).addClass(_class);
setTimeout(function () {
$(row).removeClass('increment decrement');
}, 300);
}
}
};

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.

Categories

Resources