I got undefined in the first iteration any comments is helpful to me thanks in advance
for (i = 0; i <= nummonth; i++) {
var res = compound * (Math.pow(interest, i));
res = res.toFixed(0);
var tableHTML;
var interestgained = (+res * interest)-res;
interestgained = interestgained.toFixed(0);
var powint = compound * (Math.pow(interest, i));
powint = powint.toFixed(0);
var tr = powint - compound;
var ointerest = (interest - 1)*100;
ointerest = ointerest.toFixed(0);
tableHTML = tableHTML + "<tr><td>Compound: " + i + "</td><td> " + "$"+res + "</td><td> " + ointerest + "%"+"</td><td> " + "$"+interestgained + "</td><td>"+ "$"+powint +"</td></tr>";
}
Related
Good day. I need to popluate a table from an external API and mostof the info I can get from 1 request however I need a second request to populate the developer column. However my promise function does not populate the table for some reason. Please tell me if I am doing something wrong.
The string devList is supposed to be put into the innerHTML of document.getElementById(curDev).
const req1=new XMLHttpRequest();
const rawgAPIkey="*******************"; //real key used here
const baseurl="https://api.rawg.io/api";
const url=new URL(baseurl+"/games");
var tbl=document.getElementById("gametable");
url.searchParams.set("key", rawgAPIkey);
req1.open("GET", url);
req1.responseType="text";
req1.send();
req1.onreadystatechange=function(){
if(req1.readyState===4 && req1.status===200){
var gameArr = JSON.parse(req1.responseText).results;
console.log(JSON.parse(req1.responseText).results);
for (let index = 0; index < gameArr.length; index++) {
var game;
let genres="";
let tempGenre=gameArr[index].genres;
for (let index4 = 0; index4 < tempGenre.length; index4++) {
genres += tempGenre[index4].name;
if(index4!=tempGenre.length-1){
genres+= ", ";
}
}
let platforms="";
let tempPlatforms=gameArr[index].platforms;
for (let index2 = 0; index2 < tempPlatforms.length; index2++) {
platforms += tempPlatforms[index2].platform.name;
if(index2!=tempPlatforms.length-1){
platforms+=", ";
}
}
let Tags="";
let tempTags=gameArr[index].tags;
for (let index3 = 0; index3 < 3; index3++) {
Tags += tempTags[index3].name;
if(index3!=2){
Tags+=", ";
}
}
let agerating="";
if(gameArr[index].esrb_rating!=null){
agerating=gameArr[index].esrb_rating.name;
}else{
agerating="Rating unavailiable";
}
tbl.innerHTML+=
"<tr>"
+" <td> " + " <p> " + gameArr[index].name + " </p> "
+ "<img class=\"gamepic\" src=\" "+ gameArr[index].background_image + " \" alt=\"CS:GO\">" + " </td> "
+ "<td id=\"developerID" + index + "\">" + "</td>"
+ "<td>" + gameArr[index].released + "</td>"
+ "<td>" + genres + "</td>"
+ "<td>" + agerating + "</td>"
+ "<td>" + platforms + "</td>"
+ "<td>" + Tags + "</td>";
let curDev="developerID"+index;
var url2=new URL(baseurl+"/games/"+gameArr[index].id);
url2.searchParams.set("key", rawgAPIkey);
var developer="";
async function getDev(){
let myProm= new Promise (function(success, fail){
const req2= new XMLHttpRequest();
req2.open("GET", url2);
req2.responseType="text";
req2.onload=function(){
if(req2.status===200){
var gamedevs=JSON.parse(req2.responseText).developers;
devList="";
for (let i = 0; i < gamedevs.length; i++) {
devList += gamedevs[i].name + " ";
}
success(devList);
}else{
fail("Developer unavailable");
}
};
req2.send();
});
document.getElementById(curDev).innerHTML= await myProm;
}
getDev();
}
}
}
EDIT 2:
Got it working by doing the following where I just populated the table in the same function where I set devList thus I am not using promises anymore:
async function popdevs(){
let req2= new XMLHttpRequest();
req2.open("GET", url2);
req2.responseType="text";
req2.onload=function(){
if(req2.status===200){
var gamedevs=JSON.parse(req2.responseText).developers;
devList="";
for (let i = 0; i < gamedevs.length; i++) {
devList += gamedevs[i].name + " ";
}
document.getElementById(curDev).innerHTML= devList;
//console.log(devList);
//success(devList);
return devList;
}else{
//console.log("Hello");
return "developer unavailable";
}
};
req2.send();
}
popdevs();
I have tried everything I can think of to resolve the fact that my variable is returning 'undefined'.
I have gone console.log crazy checking everything is working as it should be and am now up against the proverbial brick wall.
The script is located just before the closing body tag.
I tried putting it in the head section of the page but this began returning NaN on the variables R and X.
Putting the variables just after the opening script tag before calling the function did likewise. I am somewhat new to javascript and would very much appreciate any help.
function DisplayInputValues() {
var funds = document.getElementById("funds").value;
var s = document.getElementById("sum").innerText;
var j = document.getElementById('debt').value; //number of input fields
var txtin; //class name of text input element
var numin; // class name of number input element
var L = 0;
while (L < j) {
console.log('funds= ' + funds); //just checking amount of funds shows correctly
console.log('debt = ' + s); //just checking Debt sum shows correctly
console.log('Loop = ' + L);
var userinput1 = document.getElementsByClassName('txtin')[L].value;
console.log('Loop = ' + L + ' Text input = ' + userinput1);
document.getElementById("showresults").innerHTML += userinput1 + "<br />";
var userinput2 = document.getElementsByClassName('numin')[L].value;
console.log('Loop = ' + L + ' Number input = ' + userinput2);
document.getElementById("showresults").innerHTML += userinput2 +
"<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
var FP = funds / 100; // 1% of funds available
var SP = s / 100; // 1% of debt total
var R = userinput2 / SP;
R = R.toFixed(2);
var X = FP * R;
X = X.toFixed(2); //amount to offer in settlement
console.log('Loop = ' + L + ' FP = ' + FP);
console.log('Loop = ' + L + ' SP = ' + SP);
console.log('Loop = ' + L + ' R = ' + R);
console.log('Loop = ' + L + ' X = ' + X);
console.log('Loop = ' + L + ' Amount to offer = ' + X);
console.log('');
L = L + 1;
}
}
Output everything after calculation
X is used before you declared it. In your original code you had
document.getElementById("showresults").innerHTML += userinput2 + "<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
before X was declared so of course it is going to give you undefined
I have changed the order of things so that X is first calculated then used
var userinput1 = document.getElementsByClassName('txtin')[L].value;
var userinput2 = document.getElementsByClassName('numin')[L].value;
var FP = funds / 100; // 1% of funds available
var SP = s / 100; // 1% of debt total
var R = userinput2 / SP;
R = R.toFixed(2);
var X = FP * R;
X = X.toFixed(2); //amount to offer in settlement
console.log('Loop = ' + L + ' Text input = ' + userinput1);
document.getElementById("showresults").innerHTML += userinput1 + "<br />";
console.log('Loop = ' + L + ' Number input = ' + userinput2);
document.getElementById("showresults").innerHTML += userinput2 +
"<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
I have this code:
for(var i = 0; i < localStorage.length; i++){
var dataNya = JSON.parse(localStorage.key(i));
// console.log(dataNya);
var displayUlit = "";
displayUlit += "<br/>";
var spaceTo = "";
spaceTo += " || ";
console.log(dataNya);
var keme = localStorage.getItem(localStorage.key(i));
$("#pangDisplay").append(dataNya + spaceTo + "<button class='pangEdit' value="+dataNya+">"+JSON.parse(keme)+"</button>" + " " + displayUlit);
console.log(JSON.parse(keme));
// localStorage.setItem(JSON.stringify(dataNya), JSON.stringify("complete"));
}
$(".pangEdit").click(function(e){
e.preventDefault();
var pangInput = $(".pangEdit").val();
console.log(pangInput);
localStorage.setItem(JSON.stringify(pangInput), JSON.stringify("complete"));
});
i want to get the key of the localstorage where i can pass the data and update its value. help me thanks
You can use an attached data attributes in jQuery for this:
for (var i = 0; i < localStorage.length; i++) {
var dataNya = localStorage.key(i);
var displayUlit = "";
displayUlit += "<br/>";
var spaceTo = "";
spaceTo += " || ";
var keme = localStorage.getItem(dataNya);
var button = "<button class='pangEdit' data-storagekey='" + dataNya + "' value='" + dataNya + "'>" + keme + "</button>";
$("#pangDisplay").append(dataNya + spaceTo + button + " " + displayUlit);
}
$(".pangEdit").click(function(e) {
e.preventDefault();
var dataNya = $(this).data('storagekey');
localStorage.setItem(dataNya, "complete");
});
I have this function in javascript that is supposed to generate a table in HTML anddisable. select elements that have an id with a date prior to teoday. It seems to be working fine, except that every now and then, not always,it leaves some of the selects without disabling. Could anyone give me a lead as to why this could be happening? I am completely stuck, please help!!!
function llenaDatosTabla(){
_fecha = $("#fechaFinal").val();
_tiendaId = $("#cajaOp_tienda").val();
var errorcampos = 0;
if(_tiendaId == 0){
mensajePop("Introduzca una tienda");
errorcampos = 1;
}else if(_fecha == "" || _fecha==null){
mensajePop("Introduzca una fecha");
errorcampos = 1;
}
if(errorcampos==0){
lightboxLoading("loadingData","divLoading");
invocarJSONServiceAction('consultaTurnoXTiendaXFechaGuardadaXPuesto', {
tiendaId: _tiendaId,
fecha: _fecha},'rh_datosTurnosEmp',
null,
null);
rh_datosTurnosEmp =function(data){
if (data.resultado!=null && data.resultado!=undefined){
datastring = "<table id='dataHorarios'>";
if(data.resultado.indicadorGuardado ==0){
$("#letreroguardados").html("Los horarios NO han sido guardados");
}
else{
$("#letreroguardados").html("");
}
var subtitran = "" + data.resultado.fechaInicial + " - " + data.resultado.fechaFinal;
$("#subtitran").html(subtitran);
lideresxtienda = 0;
var extcount = 0;
var descont = 0;
adeshabilitar = new Array();
for (var i=0;i<data.resultado.turnosXUsuario.length;i++){
var rowcolor = i%2;
var rowstyle="";
var turnos = data.resultado.turnosXUsuario;
var hoy = new Date();
var fi = data.resultado.fechaInicial.split("/");
var finif = new Date(parseInt(fi[2]), parseInt(fi[1])-1, parseInt(fi[0]));
var options = "";
var turnosAplicables = new Array();
var tipoEmp = data.resultado.turnosXUsuario[i].puestoId;
if(rowcolor==0){
rowstyle = "rblanco";
}
else{
rowstyle="rgris";
}
if(tipoEmp == 1){
turnosAplicables = turnosOp;
}else if(tipoEmp == 2){
turnosAplicables = turnosEn;
lideresxtienda++;
}else if(tipoEmp == 3){
turnosAplicables = turnosLi;
lideresxtienda++;
}else{
turnosAplicables = turnosXId;
}
options = "<option value=0> Sin Definir</option>";
for(var j=0; j<turnosAplicables.length; j++){
options = options + "<option value=" + turnosAplicables[j][0] + ">" + turnosAplicables[j][1] + "</option>";
}
var fechalunes = new Date();
fechalunes.setDate(finif.getDate());
var cllunes = "";
var fechalunesf = ("0" + fechalunes.getUTCDate()).slice(-2)+"/"+("0" + (fechalunes.getUTCMonth()+1)).slice(-2) +"/"+ fechalunes.getUTCFullYear() ;
if(fechalunes<=hoy){cllunes= "disabled";}
var fechamartes = new Date();
fechamartes.setDate(finif.getDate() + 1);
var clmartes = "";
var fechamartesf = ("0" + fechamartes.getUTCDate()).slice(-2)+"/"+("0" + (fechamartes.getUTCMonth()+1)).slice(-2) +"/"+ fechamartes.getUTCFullYear() ;
if(fechamartes<=hoy){clmartes= "disabled";}
var fechamiercoles = new Date();
fechamiercoles.setDate(finif.getDate() + 2);
var clmiercoles = "";
var fechamiercolesf = ("0" + fechamiercoles.getUTCDate()).slice(-2)+"/"+("0" + (fechamiercoles.getUTCMonth()+1)).slice(-2) +"/"+ fechamiercoles.getUTCFullYear() ;
if(fechamiercoles<=hoy){clmiercoles= "disabled"; }
var fechajueves = new Date();
fechajueves.setDate(finif.getDate() + 3);
var cljueves = "";
var fechajuevesf = ("0" + fechajueves.getUTCDate()).slice(-2)+"/"+("0" + (fechajueves.getUTCMonth()+1)).slice(-2) +"/"+ fechajueves.getUTCFullYear() ;
if(fechajueves<=hoy){cljueves= "disabled";}
var fechaviernes = new Date();
fechaviernes.setDate(finif.getDate() + 4);
var clviernes = "";
var fechaviernesf = ("0" + fechaviernes.getUTCDate()).slice(-2)+"/"+("0" + (fechaviernes.getUTCMonth()+1)).slice(-2) +"/"+ fechaviernes.getUTCFullYear() ;
if(fechaviernes<=hoy){clviernes= "disabled";}
var fechasabado = new Date();
fechasabado.setDate(finif.getDate() + 5);
var clsabado = "";
var fechasabadof = ("0" + fechasabado.getUTCDate()).slice(-2)+"/"+("0" + (fechasabado.getUTCMonth()+1)).slice(-2) +"/"+ fechasabado.getUTCFullYear() ;
if(fechasabado<=hoy){clsabado= "disabled"}
var fechadomingo = new Date();
fechadomingo.setDate(finif.getDate() + 6);
var cldomingo = "";
var fechadomingof = ("0" + fechadomingo.getUTCDate()).slice(-2)+"/"+("0" + (fechadomingo.getUTCMonth()+1)).slice(-2) +"/"+ fechadomingo.getUTCFullYear() ;
if(fechadomingo<=hoy){cldomingo= "disabled";}
datastring = datastring + "<tr class=" + rowstyle +"><td class='connom' id='"+ turnos[i].usuarioId +"'>" + turnos[i].nombre + "</td>"
+ "<td class='conpues' id ='"+turnos[i].puestoId+"'>" + turnos[i].puesto + "</td>"
+ "<td class='consele ' id='"+ fechalunesf + "'><select "+ cllunes +" id='lunes"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechamartesf + "'><select "+ clmartes +" id='martes"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechamiercolesf + "'><select "+ clmiercoles +" id='miercoles"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechajuevesf + "'><select "+ cljueves +" id='jueves"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechaviernesf + "'><select "+ clviernes +" id='viernes"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechasabadof + "'><select "+ clsabado +" id='sabado"+turnos[i].usuarioId+"'>" + options + "</select></td>"
+ "<td class='consele ' id='"+ fechadomingof + "'><select "+ cldomingo +" id='domingo"+turnos[i].usuarioId+"'>" + options + "</select></td>";
setters[extcount] = new Array();
setters[extcount][0] = "#lunes"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[0].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#martes"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[1].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#miercoles"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[2].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#jueves"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[3].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#viernes"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[4].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#sabado"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[5].turnoId; extcount++;
setters[extcount] = new Array();
setters[extcount][0] = "#domingo"+turnos[i].usuarioId;
setters[extcount][1] = turnos[i].turnoXFecha[6].turnoId; extcount++;
}
datastring = datastring + "</tr></table> ";
$("#dataTHorarios").html(datastring);
for(var i = 0; i< setters.length; i++){
$(setters[i][0]).val(setters[i][1]);
}
if (logOcultaLoading>0)
ocultaLoadingPers('loadingData');
}else{
if (logOcultaLoading>0)
ocultaLoadingPers('loadingData');
}
};
}
}
See Add days to JavaScript Date. The top answer reveals that .setDate is unreliable in some cases.
Therefore, the code for each day should be changed from
var fechadomingo = new Date();
fechadomingo.setDate(finif.getDate() + 6);
to
var fechadomingo = new Date(finif.getTime());
fechadomingo.setDate(finif.getDate() + 6);
I'm writing a script which creates a table with 4 columns. The columns are N, N * 10, N * 100 and N * 1000. I managed to create the first two columns, but now I'm stuck. How should I refactor my code?
var n;
var m1 = 10;
var m2 = 100;
var m3 = 1000;
document.writeln("<table>");
document.writeln("<h1>Calculating Compound Interest</h1>");
document.writeln("<thead><tr><th>N</th>");
document.writeln("<th>N * 10</th>");
document.writeln("<th>N * 100</th>");
document.writeln("<th>N * 1000</th>");
document.writeln("</tr></thead><tbody>");
for (var number = 1; number <= 5; number++) {
n = number * m1;
if (number % 2 !== 0)
document.writeln("<tr class='oddrow'><td>" + number +
"</td><td>" + n.toFixed(0) + "</td></tr>");
else
document.writeln("<tr><td>" + number +
"</td><td>" + n.toFixed(0) + "</td></tr>");
}
document.writeln("</tbody></table>");
change your for loop to following:
for ( var number = 1; number <= 5; ++number )
{
n = number * m1;
if ( number % 2 !== 0 )
document.writeln( "<tr class='oddrow'><td>" + number + "</td>");
else
document.writeln( "<tr><td>" + number + "</td>");
document.writeln("<td>" + n.toFixed(0) + "</td>" );
n = number * m2;
document.writeln("<td>" + n.toFixed(0) + "</td>" );
n = number * m3;
document.writeln("<td>" + n.toFixed(0) + "</td></tr>" );
}
You have to add two more td's where you will put the result of number*2 and number*m3
Also I would recommend you using innerHTML to write complete desired html rather than using document.writeIn every time
See The Solution on js fiddle
var n;
var m1 = 10;
var m2 = 100;
var m3 = 1000;
var heading_html = "<h1>Calculating Compound Interest</h1>" ;
var tbable_html = "<table border=1>";
tbable_html += "<thead><tr><th>N</th>";
tbable_html += "<th>N*10</th>";
tbable_html += "<th>N*100</th>";
tbable_html += "<th>N*1000</th>";
tbable_html +="</tr></thead><tbody>";
for (var number = 1; number <= 5; ++number) {
n1 = number * m1;
n2 = number * m2;
n3 = number * m3;
if (number % 2 !== 0)
tbable_html +="<tr class='oddrow'><td>" + number + "</td><td>" +
n1.toFixed(0)+"</td><td>"+n2.toFixed(0)+"</td><td>"+n3.toFixed(0)+"</td></tr>";
else
tbable_html +="<tr><td>" + number + "</td><td>" + n1.toFixed(0) +
"</td><td>" + n2.toFixed(0) + "</td><td>" + n3.toFixed(0) + "</td></tr>";
}
tbable_html +="</tbody></table>";
document.write(heading_html+tbable_html);
Try this:
var n = [1, 2, 3, 4, 5].reduce(function (string, n) {
return string + "<tr class='" + (n % 2 ? "oddrow" : "evenrow") + "'>" +
[n, 10 * n, 100 * n, 1000 * n].reduce(td, "") + "</tr>";
}, "");
document.body.innerHTML += "<table><thead><tr>" +
"<th>N</th><th>N * 10</th><th>N * 100</th><th>N * 1000</th>" +
"</tr></thead><tbody>" + n + "</tbody></table>";
function td(string, n) {
return string + "<td>" + n + "</td>";
}
See the demo: http://jsfiddle.net/7uPVH/
If you don't want to use .reduce then you could rewrite the above code as follows:
var n = "";
for (var i = 1; i <= 5; i++) {
n += "<tr class='" + (i % 2 ? "oddrow" : "evenrow") + "'>";
n += "<td>" + i + "</td>";
n += "<td>" + 10 * i + "</td>";
n += "<td>" + 100 * i + "</td>";
n += "<td>" + 1000 * i + "</td>";
n += "</tr>";
}
document.body.innerHTML += "<table><thead><tr>" +
"<th>N</th><th>N * 10</th><th>N * 100</th><th>N * 1000</th>" +
"</tr></thead><tbody>" + n + "</tbody></table>";
See the demo: http://jsfiddle.net/7uPVH/1/