function for disabling select elements not always working - javascript

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);

Related

Why there is an error in var in line 44 (var finalURL = formURL + formData; and line 46

When I am saving or running this it shows
syntax error unexpected token var in line 44 var finalURL = formURL + formData;
I followed this step by step from a tutorial and that one ran smoothly. But I am running into this error even though all looks good to me.
It shows no error when I place these two variables above formUrl and formData but will that be ok to do?
function autoEntry() {
var wrkBk = SpreadsheetApp.getActiveSpreadsheet();
var wrkSht = wrkBk.getSheetByName("Data");
var formURL = "";
var formData = "";
var email = "";
var wherefound = "";
var contest = "";
var contest2 = "";
var p1name = "";
var phone = "";
var email1 = "";
var college = "";
var team = "";
var add = "";
var p2name = "";
var p2phone = "";
var p2email = "";
var noOfrows = 11;
for (i=2;i<=noOfrows;i++)
{
email = wrkSht.getRange("A" + i).getDisplayValue();
wherefound = wrkSht.getRange("B" + i).getDisplayValue();
contest = wrkSht.getRange("C" + i).getDisplayValue();
contest2 = wrkSht.getRange("D" + i).getDisplayValue();
p1name = wrkSht.getRange("E" + i).getDisplayValue();
phone = wrkSht.getRange("F" + i).getDisplayValue();
email1 = wrkSht.getRange("G" + i).getDisplayValue();
college = wrkSht.getRange("I" + i).getDisplayValue();
team = wrkSht.getRange("I" + i).getDisplayValue();
add = wrkSht.getRange("J" + i).getDisplayValue();
p2name = wrkSht.getRange("H" + i).getDisplayValue();
p2phone = wrkSht.getRange("F" + i).getDisplayValue();
p2email = wrkSht.getRange("G" + i).getDisplayValue();
formURL ="https://docs.google.com/forms/d/1CBfK0vGAJhU2zUlAYQS75qX0a79n52o_j5xRobd9ElM/formResponse?&pageHistory=0,1,2"
formData = "&emailAddress=" + email + "&entry.985288382=" + wherefound + "&entry.1403417779=" + contest + "&entry.1403417779=" + contest2 + "&entry.840653442=" + p1name + "&entry.333445391=" + phone + "&entry.1710226101" + email1 + "&entry.1025973123=" + college + "&entry.1833616786=" + team + "&entry.1627866442=" + add + "entry.2057643731=" + p1name + "&entry.1510242317=" + phone + "&entry.1096702233" + email1 + "&entry.1638965943=" + p2name + "&entry.699293629=" + p2phone + "&entry.811372241=" + p2email +
var finalURL = formURL + formData;
var options = {
"method": "post"
};
UrlFetchApp.fetch(finalURL, options);
}
}
You have a + at the end of line where you are assigning formData.
formData = "&emailAddress=" + email + "&entry.985288382=" + wherefound + "&entry.1403417779=" + contest + "&entry.1403417779=" + contest2 + "&entry.840653442=" + p1name + "&entry.333445391=" + phone + "&entry.1710226101" + email1 + "&entry.1025973123=" + college + "&entry.1833616786=" + team + "&entry.1627866442=" + add + "entry.2057643731=" + p1name + "&entry.1510242317=" + phone + "&entry.1096702233" + email1 + "&entry.1638965943=" + p2name + "&entry.699293629=" + p2phone + "&entry.811372241=" + p2email +
Removing that should solve the error.

How to fix undefined in first iteration on javascript

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>";
}

How to create a dynamic table in jQuery?

I want to create a dynamic table in jQuery. But my code creates a table for each of my element.
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Which part of my code is wrong?
as you were adding table in for loop, so it was creating table for each item.Try this:
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 = content;
}
content += "</table>"
// you can also assign spl2 = content; over here.
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
var content = "<table>";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Updated your script

Undefined Variable In document.write [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting "toggleOnlyRelatedPosts is not defined " in Chrome console and the script doesn't work. I'm working on this script and I've gotten lost after adding so many variables. I'm not that good at this sort of thing and to me it looks clearly defined, but I guess it's not. Chrome marks the error at the document.write
Here is the script:
<script type="text/javascript">
//<![CDATA[
function postGrabber(json) {
// The Magic
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
// Thumbnail Stuff
var orgImgUrl = json.feed.entry[i].media$thumbnail.url ? json.feed.entry[i].media$thumbnail.url : 'http://1.bp.blogspot.com/-mxinHrJWpBo/VD6fqbvI74I/AAAAAAAAcn8/LslulDeOROg/s72-c/noimage-chalkboard.jpg';
var newImgUrl = orgImgUrl.replace('s72-c', 's' + imgSize + '-c');
var imgTag = '<a class="item-link-post" href="' + postUrl + '"><img class="item-img-thumbnail" src="' + newImgUrl + '" width="' + imgSize + '" height="' + imgSize + '"/></a>';
var authorName = json.feed.entry[i].author[0].name.$t;
var authorURL = json.feed.entry[i].author[0].uri.$t;
var authorOriImgUrl = json.feed.entry[i].author[0].gd$image.src;
var authorNewImgUrl = authorOriImgUrl.replace('s512-c', 's' + authorImgSize + '-c');
var authorImgTag = '<a class="item-link-author" href="' + authorURL + '" target="_blank" rel="nofollow"><img class="item-img-author" src="' + authorNewImgUrl + '" alt="' + authorName + '"/></a>';
var postLabel = json.feed.category[i].term;
var postLabelUrl = '/-/' + postLabel + '';
// Standard Stuff
var postTitle = json.feed.entry[i].title.$t;
var postCommentCount = json.feed.entry[i].thr$total.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, '' + summaryLength + '');
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postDate = json.feed.entry[i].updated.$t ? json.feed.entry[i].updated.$t : json.feed.entry[i].published.$t;
var shortDate = postDate.substring(0,10);
// Let's Make Options Here
var toggleImg = showImg ? '' + imgTag + '' : '';
var toggleTitle = showTitle ? '<h1 class="item-title">' + postTitle + '</h1>' : '';
var toggleSummary = showSummary ? '<p class="item-snippet">' + postContent + '</p>' : '';
var toggleDate = showDate ? '<span class="item-date">' + shortDate + '</span>' : '';
var toggleAuthorImg = showAuthorImg ? '' + authorImgTag + '' : '';
var toggleCommentCount = showCommentCount ? '<span class="item-comment-count">' + postCommentCount + '</span>' : '';
var toggleOnlyRelatedPosts = showOnlyRelatedPosts ? '' + postLabelUrl + '' : '';
// The Output
var itemPost = '<div class="item-post"><div class="item-imgs">' + toggleImg + toggleAuthorImg + '</div>' + toggleCommentCount + '<a class="item-link" href=' + postUrl + '>' + toggleTitle + '</a>' + toggleSummary + toggleDate + '</div>';
// Let's Write It Down
document.write(itemPost);
}
}
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
var imgSize = 96;
var summaryLength = 142;
var authorImgSize = 36;
var showImg = true;
var showTitle = true;
var showSummary = true;
var showDate = true;
var showAuthorImg = true;
var showCommentCount = true;
var showOnlyRelatedPosts = true;
document.write('<script type="text/javascript" src="/feeds/posts/summary' + toggleOnlyRelatedPosts + '?orderby=published&max-results=5&alt=json-in-script&callback=postGrabber"><\/script>');
//]]>
</script>
The variable toggleOnlyRelatedPosts is declared in the scope of the function postGrabber. It is therefore indeed undefined in the line with the document.write, where you try to use it.
If you wish to use those variables outside the function you have to declare them outside the function.
Read up on the concept of 'scope', it's pretty fundamental knowledge in any programming language.

local storage iteration get the value of clicked button inside for loop

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");
});

Categories

Resources