Cant call Jquery function in if loop - javascript

my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}

I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });

Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did

Related

Bootstrap modal populated by selected row in table data

The code below works fine on my computer, however when I am trying it on different workstations it does not work unless you do a hard refresh SHIFT + F5 then it will work but, when the page is reloaded it will go back to not working. Any help if you can tell me where this script is wrong would be greatly appreciated.
function run() {
var table = document.getElementById('call-logs-table');
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
rows[i].onclick = function (event) {
var cells = this.cells;
var person_contacted = cells[0].innerHTML;
var date = cells[1].innerHTML;
var c_purpose = cells[2].innerHTML;
var c_notes = cells[3].innerHTML;
var sales_rep = cells[4].innerHTML;
var timestamp = cells[5].innerHTML;
var potential = cells[6].innerHTML;
var catalog_num = cells[7].innerHTML;
var dateplanner_num = cells[8].innerHTML;
var calendar_num = cells[9].innerHTML;
document.getElementById('call-log-title').innerHTML = 'Call Log Entered at ' + timestamp + ' by ' + sales_rep;
document.getElementById('lbl_contact').innerHTML = person_contacted;
document.getElementById('lbl_date').innerHTML = date;
document.getElementById('lbl_catalogs').innerHTML = catalog_num;
document.getElementById('lbl_calendars').innerHTML = calendar_num;
document.getElementById('lbl_planners').innerHTML = dateplanner_num;
document.getElementById('lbl_purpose').innerHTML = c_purpose;
document.getElementById('lbl_notes').innerHTML = c_notes;
document.getElementById('lbl_potential').innerHTML = potential;
};
}
}
window.onload = function() { run(); }

Execute a second function when the first complete

I have a GS code with three different functions that are activated with a form submission.
The first function:
function processForm(formObject){
if(formObject.RecId && checkID(formObject.RecId)){
updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId));
}else{
appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange);
var form = FormApp.create(formObject.nombre)
.setAllowResponseEdits(false)
.setCollectEmail(false)
.setDescription(formObject.fechaprev)
.setRequireLogin(false)
.setShowLinkToRespondAgain(false);
var newname = formObject.nombre;
form.setDestination(FormApp.DestinationType.SPREADSHEET, globalVariables().spreadsheetId);
}
When this first function completes I need to run this other two functions:
function ordenarData(formUrl){
var ss = SpreadsheetApp.openById(globalVariables().spreadsheetId);
var sheetNameArray = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
sheetNameArray.push(sheets[i].getName());
}
var ordenado = sheetNameArray.sort();
for( var j = 0; j < sheets.length; j++ ) {
ss.setActiveSheet(ss.getSheetByName(sheetNameArray[j]));
ss.moveActiveSheet(j + 1);
var last_element = sheetNameArray[sheetNameArray.length - 1];
Logger.log(last_element);
}
completarData(formUrl,last_element);
}
function completarData(formUrl,last_element){
var ss = SpreadsheetApp.openById(globalVariables().spreadsheetId);
var hojaData = ss.getSheetByName("Data")
var celdaNEv = "=COUNT(\'"+ last_element + "\'\!\A\:\A\)";
var celdaSatisf = "=IFERROR((AVERAGE(\'"+ last_element +"\'\!\C\:\C)/10);0)";
var celdaPEv = '=IFERROR(O'+ hojaData.getLastRow() +'/N' + hojaData.getLastRow() +';0)';
var celdaPAs = '=IFERROR(N'+hojaData.getLastRow()+'/M'+hojaData.getLastRow()+';0)';
var celdaForm = "<a href=" + formUrl + " target='_blank' class='btn btn-primary btn-xs'><i class='fas fa-file-alt'></i></a>";
var celdaTh = '=IFERROR(ROUND(L'+hojaData.getLastRow()+'*N'+hojaData.getLastRow()+'; 0);0)';
var celdaMhr = '=IFERROR(ROUND(T'+hojaData.getLastRow()+'/M'+hojaData.getLastRow()+'; 2);0)';
var formulas = [
[celdaNEv, celdaSatisf, celdaPEv, celdaPAs, celdaForm, celdaTh, celdaMhr]
];
var formatos = [
["###", "0.00%", "0.00%", "0.00%", "", "####", "0.00"]
];
var cell = hojaData.getRange("O"+hojaData.getLastRow()+":U"+hojaData.getLastRow()+"").setNumberFormats(formatos);
cell.setValues(formulas);
}
As you can see, the first function generates a GForm and set the destination to an existing ssheet. Then, with ordenarData() I want to order the sheets and get the name of the last tab. My problem is that if a link processForm() to the second function, they run at the same time and theres no time to generate the new tab, so the function does not work fine.
How can I set that the function ordenarData() runs only when processForm() has finished?
If you know any other way to get the name of the Tab which is generate with FormApp.create().setDestination it will be also okay for me.
Solve!
SpreadsheetApp.flush() works fine for me: getSheets() Google Apps Script multiple calls issue

Nesting a function returning NaN

I am running into an error when I try nesting a simple counter function inside an existing function. I know some people frown upon this, so if there is any other way of doing this, it would be greatly appreciated. Basically, I am calling a function to parse a JSON string to get 3 numbers. I would like to animate those 3 numbers with a counter every time a new calculation is made. My instinct is to place this counter function inside of the same for loop that runs to get the numbers themselves. Doing so returns NaN. I'm sure there is something very little that I am missing here that I am hoping someone can pick up on.
Code:
var text = '{JSON data}'
var obj = JSON.parse(text);
function calculate() {
var e = document.getElementById("ltSpecialtyList");
var selectedSpec = e.options[e.selectedIndex].text;
console.log(selectedSpec);
var x = document.getElementById("ltLocationList");
var selectedState = x.options[x.selectedIndex].text;
console.log(selectedState);
for (i = 0; i < obj.values.length; i++)
{
if (obj.values[i].State == selectedState && obj.values[i].Specialty == selectedSpec)
{
// DISPLAY RESULTS DIV (JQUERY)
var $resultsDiv = $("#ROI-results");
$resultsDiv.fadeIn();
// CAPTURE HEADER SPAN NAMES
var headerState = document.getElementById("header-state-name");
var headerSpec = document.getElementById("header-specialty-name");
// CLEAR STATE AND SPECIALTY FROM SPAN
headerState.innerHTML = "";
headerSpec.innerHTML = "";
// ADD SELECTED STATE AND SPECIALTY
headerState.innerHTML += selectedState;
headerSpec.innerHTML += selectedSpec;
// CAPTURE RESULT DATA DIVS
var permResults = document.getElementById("ROI-results-perm-data");
var locumResults = document.getElementById("ROI-results-locums-data");
var uncollectedResults = document.getElementById("ROI-results-uncollected-data");
// CLEAR DATA DIVS
permResults.innerHTML = "";
locumResults.innerHTML = "";
uncollectedResults.innerHTML = "";
//POPULATE DIV WITH DATA
permResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Permanent + "</p>";
locumResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Locums + "</p>";
uncollectedResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Gross + "</p>";
}
// COUNTER
$('.ROI-results-data-number').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
}

Writing from a custom type to an array in Javascript

I've been stuck for a few days now on this. I can get my albums to write to the console but I can't figure out how to get them to write into an array. The code works so when I click "Show Albums" button, it returns nothing other than [Object, object]. Can anyone help me figure out how to write the new albums to the array so it displays properly? Thanks in advance.
(function() {
var name = document.getElementById("name");
var year = document.getElementById("year");
var showbutton = document.getElementById("showlist");
var submitbutton = document.getElementById("submit");
var validate = document.getElementById("validate");
var albumlist = [];
var albums = function album(name, year) {
this.name = name;
this.year = year;
this.album = function() {
return ((this.name + ", " + this.year));
};
}
albums.prototype.genre = "rock";
var album1 = new albums("album1", "1999");
var album2 = new albums("album2", "2000");
var album3 = new albums("album3", "2001");
var album4 = new albums("album4", "2002");
var album5 = new albums("album5", "2003");
albumlist.push(album1, album2, album3, album4, album5);
showbutton.onclick = function() {
for (var i = 0; i < albumlist.length; i++) {
console.log(albumlist[i]);
}
document.getElementById("myalbums").innerHTML = albumlist.sort() + "<br/>";
}
document.getElementById("myalbums").innerHTML = albumlist.sort() + "<br/>";
Take a look at what this line does. This takes an array, which is an object with many functions, keys, etc, and tries to plot in on the page.
It will not be possible, since javascript doesn't know how to turn that array into a string.
For you to do that, you have to first create the string you want and than plot it on the page.
You need to iterate through the items and generate a string, for example:
var names = "";
for(var i = 0; i < albumlist.length; i++){
names += albumlist[i].name + ' ';
}
and then replace it on the html:
document.getElementById("myalbums").innerHTML = names + "<br/>";

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources