each method being skipped in debug mode - javascript

here is some JavaScript that I am testing:
var filters;
$(".arrow-up").unbind("click").click(function (event) {
var clickedArrow = $(this);
var id = clickedArrow.attr('data-id');
var select = document.getElementById(id);
var option = select.options[select.selectedIndex];
var filters;
$(".search").each(function () {
var SearchText = this.value;
var id;
if (!checkEmpty(SearchText)) {
switch (this.id) {
case "one":
id = 1;
break;
case "two":
id = 2;
break;
case "three":
id = 3;
break;
case "four":
id = 4;
break;
case "five":
id = 5;
break;
case "six":
id = 6;
break;
case "seven":
id = 7;
break;
case "eight":
id = 8;
break;
}
var filter = document.getElementById(id);
var filterOption = filter.options[filter.selectedIndex].text;
filters += '&col=' + filterOption;
filters += '&col=' + SearchText;
}
});
var cols;
/* Get all of the drop downs for the columns */
for (var i = 1; i <= 8; i++) {
var txt;
var colVal = document.getElementById(i);
txt = colVal.options[colVal.selectedIndex].text;
cols += '&col=' + txt;
}
var url = '/AccountManagement/SortAscend';
var formData = {
option: option,
filters: filters,
cols: cols
}
var posting = $.post(url, formData, function (data, textstatus) {
//spinner = new Spinner(opts).spin(target);
StartSpinner();
}, "json");
posting.done(function (data) {
ReloadTable(data);
StopSpinner();
});
});
When I debug this in chrome, it skips the $(".search").each(function() { part - it just skips to the end of the method, therefore it never goes over any of the eight items and the filters variable remains "undefined" I am not sure why.

Please try these changes and tell me if that still just goes by the each. Because I am using each just as you do and it works perfectly. Maybe I would also change the switch to an "associative array"
var numbers = {"one":1,"two":2...};
And then
id = numbers[$(this).attr("id")]
But first try the code below.
var filters;
$(".arrow-up").unbind("click").click(function (event) {
var clickedArrow = $(this);
var id = clickedArrow.data('id');
var select = $('#'+id);
var option = $(select + '> option:selected');
var filters;
$(".search").each(function () {
var SearchText = $(this).val();
var id;
if (!checkEmpty(SearchText)) {
switch ($(this)attr("id")) {
case "one":
id = 1;
break;
case "two":
id = 2;
break;
case "three":
id = 3;
break;
case "four":
id = 4;
break;
case "five":
id = 5;
break;
case "six":
id = 6;
break;
case "seven":
id = 7;
break;
case "eight":
id = 8;
break;
}
var filter = document.getElementById(id);
var filterOption = filter.options[filter.selectedIndex].text;
filters += '&col=' + filterOption;
filters += '&col=' + SearchText;
}
});
var cols;
/* Get all of the drop downs for the columns */
for (var i = 1; i <= 8; i++) {
var txt;
var colVal = document.getElementById(i);
txt = colVal.options[colVal.selectedIndex].text;
cols += '&col=' + txt;
}
var url = '/AccountManagement/SortAscend';
var formData = {
option: option,
filters: filters,
cols: cols
}
var posting = $.post(url, formData, function (data, textstatus) {
//spinner = new Spinner(opts).spin(target);
StartSpinner();
}, "json");
posting.done(function (data) {
ReloadTable(data);
StopSpinner();
});
});

Related

Javascript filter don't work on Google Script Apps function

I'm trying to use a filter on a HTML page.
But something is going wrong when turning the spreadsheet data into a slice: userCodeAppPanel:53 Uncaught TypeError: Cannot read property 'filter' of undefined at Pesquisa (userCodeAppPanel:53) at HTMLButtonElement.Teste (userCodeAppPanel:94)
I got inspired by this video lesson: https://www.youtube.com/watch?v=1CSPpsBGlQ0&t=123s
I suspect it is something with the CarregaDados() function initialization.
There is a field where I choose the type of equipment and an input to search for the serial number
I am using a table inside a sweetAlert2 to show the spreadsheet data.
but no data in the tag appears.
The Code:
HTML
<script>
var dado;
function CarregaDados() {
var Tipo_pesquisa = document.getElementById("Tipop").value;
switch (Tipo_pesquisa) {
case 'Transmissor':
var flag = 'Transmissores';
break;
case 'Central':
var flag = 'Centrais';
break;
case 'Repetidor':
var flag = 'Repetidores';
break;
case 'Gateway':
var flag = 'Gateways';
break;
case 'Mobile':
var flag = 'Mobiles';
break;
};
google.script.run.withSuccessHandler(function(retorna_dado) {
dado = retorna_dado.slice();
}).PesquisaDado(flag);
}
function Pesquisa() {
Swal.fire({
title: '<h1 class="hlinha">Histórico do Equipamento: </h1>',
width: 1000,
html: '<center><table class="Ptable" style="width:100%"><thead><tr class="tr"><th scope="col">' +
'<strong>Entada</strong></th><th scope="row"><strong>Modelo</strong></th>' +
'<th scope="row"><strong>SN ou MAC</strong></th><th scope="row"><strong>Ocorrência</strong></th>' +
'<th scope= "row"><strong>Status</strong></th><th scope="row"><strong>Data</strong></th><th scope="row">' +
'<strong>Observações</strong></th><th scope="row"><strong>Funcionário</strong></th></tr><tr class="tr"></thead>' +
'<tbody id="ResultadoPesquisa"></tbody></table></center><template id="Template">' +
'<tr><th scope="row"></th><td class="Modelo"></td><td class="Sn"></td><td class="ocorrencia"></td><td class="status"></td>' +
'<td class="data"></td><td class="obs"></td><td class="funcionario"></td></tr></template>',
showCloseButton: true,
showCancelButton: false,
showConfirmButton: false
})
var SN = document.getElementById("SN_Pesquisa").value.toString().toLowerCase();
var resultadoArr = dado.filter(function(r) {
return r[2].toString().toLowerCase().indexOf(SN) !== -1;
});
var caixa = document.getElementById("ResultadoPesquisa");
var template2 = document.getElementById("Template");
var template = template2.content;
resultadoArr.forEach(function(r) {
var linha = template.cloneNode(true);
var Entrada_C = linha.querySelector(".Entrada");
var Modelo_C = linha.querySelector(".Modelo");
var Sn_C = linha.querySelector(".Sn");
var ocorrencia_C = linha.querySelector(".ocorrencia");
var status_C = linha.querySelector(".status");
var data_C = linha.querySelector(".data");
var obs_C = linha.querySelector(".obs");
var funcionario_C = linha.querySelector(".funcionario");
Entrada_C.textContent = r[0];
Modelo_C.textContent = r[1];
Sn_C.textContent = r[2];
ocorrencia_C.textContent = r[3];
status_C.textContent = r[4];
data_C.textContent = r[5];
obs_C.textContent = r[6];
funcionario_C.textContent = r[7];
caixa.appendChild(linha);
});
}
function Teste(e) {
if (e.target.matches("#ResultadoPesquisa")) {
Pesquisa();
} else {
CarregaDados();
Pesquisa();
};
}
document.getElementById("Pesquisa").addEventListener("click", Teste);
</script>
gs
function PesquisaDado(Tipo) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName(Tipo);
return ws.getRange(9,3,ws.getLastRow()-9,8).getValues();
}

fabric js Cannot read property 'src' of undefined

I have a code that the src property is undefined when I want to change the source image with for loop and switch case to detect the id of image object. this my code.
function buildTable(results) {
var data = results.data;
let gbr;
for (i = 0; i < data.length; i++) {
var c = "<canvas id='can" + i + "' class='printCanvas' ></canvas><br>";
$("body").append(c);
canvas2[i] = new fabric.Canvas('can' + i + '');
canvas2[i].setWidth(298);
canvas2[i].setHeight(420);
if (data[i] != "") {
var row = data[i];
var cells = row.join(",").split(",");
// console.log(cells);
}
canvas2[i].loadFromJSON(canvas.toJSON(['id', 'qrcode']), function() {}, function(o, object) {
switch (object.id) {
case 'id':
object.text = cells[1];
break;
case 'daerah':
object.text = cells[3];
break;
case 'tgl':
object.text = cells[2];
break;
case 'qrcode':
gbr = object;
object.setSrc(makeQR(cells[1]), canvas.renderAll());
break;
default:
break;
}
console.log(gbr.src);
});
canvas2[i].renderAll();
}
}
the cause of error is happen with the following code
console.log(gbr.src);

Why do I get “undefined” in the table in my Firebase app?

I'm trying to create an app that retrieves data from Firebase and show it in a table using JavaScript. The problem is that it’s showing me “undefined” in the app and in the console and when I try to print the values directly from the functions they contain a value, so can anyone please help me with this?
This is my code:
function doSomething() {
var something = firebase.database().ref('*****');
//comment selection
something.on('value', function gotData(data) {
var values = data.val();
var keys = Object.keys(values);
var i = 0;
while (i < keys.length) {
var k = keys[i];
var comments = values[k].comment;
var idU = values[k].id;
var idS = values[k].idservice;
var nom = getuser(idU);
var service = getservice(idS);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var t = document.createTextNode(i + ':' + comments);
var t2 = document.createTextNode(nom);
var t3 = document.createTextNode(service);
td.appendChild(t);
td2.appendChild(t2);
td3.appendChild(t3);
tr.appendChild(td);
tr.appendChild(td2);
tr.appendChild(td3);
document.getElementById("commentsection").appendChild(tr);
i++;
}
}, errData);
}
function getuser(IdU) {
var users = firebase.database().ref('******');
users.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var j = 0;
while (j < keys.length) {
var k = keys[j];
if (k === IdU) {
var name = values[k].nom;
console.log(name);
return name;
break;
} else {
console.log('not found');
break;
}
j++;
}
}, errData);
}
function getservice(IdS) {
var service = firebase.database().ref('******');
service.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var s = 0;
while (s < keys.length) {
var k = keys[s];
if (k === IdS) {
var nomservice = values[k].nomservice
console.log(nomservice);
return nomservice;
break;
} else {
return false;
}
s++;
}
}, errData);
}
function errData(err) {
console.log('error!');
console.log(err);
}
This is a screenshot for what I get:

How to get both mobile and desktop score with PageSpeed

I'm trying to get page speed score for both: desktop and mobile and then pass them to #pgscore && #pgscorem inputs.
Problem is that at the end of script I get always var device == 'mobile'. It looks like it skips for loop. Any idea how could I fix it?
for (var r = 0; r < 2; r++) {
var API_KEY = 'mykey';
var device = '';
switch (r) {
case 0: device='desktop'; break;
case 1: device='mobile'; break;
};
alert(device);
var URL_TO_GET_RESULTS_FOR = 'http://www.stackoverflow.com' + '&strategy=' + device;
var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';
var callbacks = {}
function runPagespeed() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
var query = [
'url=' + URL_TO_GET_RESULTS_FOR,
'callback=runPagespeedCallbacks',
'key=' + API_KEY,
].join('&');
s.src = API_URL + query;
document.head.insertBefore(s, null);
}
function runPagespeedCallbacks(result) {
if (result.error) {
var errors = result.error.errors;
for (var i = 0, len = errors.length; i < len; ++i) {
if (errors[i].reason == 'badRequest' && API_KEY == 'yourAPIKey') {
alert('Please specify your Google API key in the API_KEY variable.');
} else {
alert(errors[i].message);
}
}
return;
}
for (var fn in callbacks) {
var f = callbacks[fn];
if (typeof f == 'function') {
callbacks[fn](result);
}
}
}
setTimeout(runPagespeed, 0);
callbacks.displayPageSpeedScore = function(result) {
var score = result.score;
Function countinues down there. Problem is here... Why I can't get variable device == 'desktop' first and then in second for loop 'mobile'? I get always 'mobile'.
switch (device) {
case 'desktop': $('#pgscore').val(score); break;
case 'mobile': $('#pgscorem').val(score); break;
};
};
};
Since I need only score, I'm using php
$jsonurl="https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&locale=pl_pl&$key";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json, true);
/* print_r(array_values($json_output));*/
echo $json_output['score'];

switch case not working properly in javascript

I Have Written This Code For Link Redirection But The Problem With The Code It Triggered Only First Case It Omits Other Cases In The Switch Statement
<script type="text/javascript">
window.onload = function () {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var string = links[i].href; //href value
var str = string;
var spl = string.split("/");
switch (spl[2]) {
case 'www.google.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
return (m);
break;
case 'www.ebay.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
return (m);
break;
default:
links[i].href = string;
}
}
}
</script>
HTML:
www.google.com</br>
www.ebay.com</br>
Remove return(m) from above code. It should work fine. It's return after first call.
Since you have return(m); here, it returns from there and do not execute the rest of the code. you can test it by putting alert("Hi"); after the return statement. This alert should not work for your code.
<script type="text/javascript">
window.onload = function () {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var string = links[i].href; //href value
var str = string;
var spl = string.split("/");
switch (spl[2]) {
case 'www.google.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
break;
case 'www.ebay.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
break;
default:
links[i].href = string;
}
}
}
</script>

Categories