I've never been good with coding and what I did was mainly PHP not javascript. This is running on a Windows server that I have no ability to install anything new on.
I have a web page that someone else built that I am trying to reformat. The current one is an OpenLayers map.
I want to take the information on the map and put it on a table.
A PowerShell script outputs data to a txt file.
The web page imports that data does a few different things to it.
I end up with three columns of stuff I want to put on the table and there just shy of 20 rows.
This is what I've tried so far.
<table id="myTable">
<tr>
<td>Office</td>
<td>Server Ping</td>
<td>Circuit Ping</td>
</table>
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = fullname;
cell2.innerHTML = pingResultHTML;
cell3.innerHTML = circuitPrimaryResultHTML;
};
If needed I can post more or all of the page's code.
I'm operating under the assumption that if the variables can be used to populate info for popups on the map I should be able to just redirect them into a table.
Edit:
Here is additional info.
This is what calls the data from the txt file.
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();
}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.open("GET","latest_results_list.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
var mySplitResult;
mySplitResult = xmlDoc.split("\r\n");
for(i = 0; i < mySplitResult.length; i++)
{
var locationStringCleaned = mySplitResult[i].replace(/(\r\n|\n|\r)/gm,"");
officeParameters = locationStringCleaned.split(",");
officelocation = officeParameters[0];
pingStatus = officeParameters[1];
pingTime = officeParameters[2];
primaryCircuit = officeParameters[3];
primaryCircuitTime = officeParameters[4];
addNewLocation(officelocation, pingStatus, pingTime, primaryCircuit, primaryCircuitTime);
This adds the site name.
if (officename == "SHO"){
fullname = "Stevens Point, WI";
} else if (officename == "RIC"){
fullname = "Richmond, VA";
} else if (officename == "DAV"){
fullname = "Davenport, IA";
} else if (officename == "GOL"){
fullname = "Goldsboro, NC";
} else if (officename == "IRV"){
fullname = "Irvine, CA";
} else if (officename == "MON"){
fullname = "Montgomery, AL";
} else if (officename == "MAD"){
fullname = "Madison, WI";
} else if (officename == "SAL"){
fullname = "Salem, OR";
} else if (officename == "SCO"){
fullname = "Scottsdale, AZ";
} else if (officename == "WES"){
fullname = "Westford, MA";
} else if (officename == "FRE"){
fullname = "Freeport, IL";
} else if (officename == "MIL"){
fullname = "Milwaukee, WI";
} else if (officename == "AVI"){
fullname = "Stevens Point, WI";
} else if (officename == "PLO"){
fullname = "Plover, WI";
} else if (officename == "MADG"){
fullname = "Madison, WI";
} else if (officename == "MADC"){
fullname = "Madison, WI";
} else if (officename == "MADR"){
fullname = "Madison, WI";
} else if (officename == "EDW"){
fullname = "Edwardsville, IL";
} else if (officename == "CHA"){
fullname = "Charlotte, NC";
These format text color based on ping after being run through some else if statements.
pingResultHTML = "<span style='color:" + pingColor + "'>" + pingResult + " (" + pingTime + " ms)</span>";
circuitPrimaryResultHTML = "<span style='color:" + linkStatusPrimaryColor + "'>" + linkStatusPrimary + " (" + linkStatusPrimaryTime+ " ms)</span>";
This is an example of the data in the txt file.
MAD,GOOD,7,GOOD,7
DAV,GOOD,30,GOOD,30
first You need to adapt data in javascript understandable form like object,map & whatever.....
then you need to just iterate over that like that-
Let Suppose data contains you map.
var rowCount=1,
table = document.getElementById("myTable"),
tbdy = document.createElement('tbody');
for (var k in data) {
var tr = document.createElement('tr');
for (var j = 0; j < 3; j++){
var td = document.createElement('td');
td.appendChild(document.createTextNode((!j)?rowCount++:(j==1)?k:device[k]));
tr.appendChild(td);
}
tbdy.appendChild(tr);
}
table.appendChild(tbdy);
I suggest use something like OOP:
function MyTable(data) {
this.data = data;
this.rows = [];
this.container = document.createElement('table');
this.body = document.createElement('tbody');
this.container.appendChild(this.body);
this.render();
}
MyTable.prototype.render = function(){
this.body.innerHTML = '';
for(var i = 0; i < this.data.length; i++){
this.rows.push(new MyRow(this.data[i]));
}
for(var j = 0; j < this.rows.length; j++) {
this.body.appendChild(this.rows[j].container);
}
}
MyTable.prototype.setData= function(data){
this.data = data;
this.rows = [];
this.render();
}
function MyRow(data) {
this.container = document.createElement('tr');
var name = document.createElement('td');
name.innerHTML = data.name;
this.container.appendChild(name);
}
var myTable = new MyTable([{name: 'Joe'}, {name: 'Pit'}]);
document.body.appendChild(myTable.container);
//data update:
myTable.setData([{name: 'Alex'}, {name: 'Stephan'}]);
myTable.render();
Related
I cannot seem to get the syntax right when targeting JSON response.
In my project I have a <div id="percentage"></div>.
I want to append the score as text to the div but i'm getting "Cannot read property 'categories' of undefined" error in the console.
I think it is a syntax error from my side.
How to fix it?
JSON:
{"lighthouseResult":{"categories":{"performance":{"score":1.0},"accessibility":{"score":0.9},"best-practices":{"score":0.92},"seo":{"score":0.8},"pwa":{"score":0.54}}}}
Javascript:
function loadAnalysis() {
var xhttp = new XMLHttpRequest();
var url = document.getElementById("url").value;
if (url == "") {
alert("Please enter URL");
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
var table = document.createElement('table');
table.setAttribute('class', 'result');
var properties = ['performance', 'accessibility', 'best-practices', 'seo', 'pwa'];
var capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.classList.add("category");
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
console.log("jsonResponse", jsonResponse);
var categories = Object.keys(jsonResponse["lighthouseResult"]);
for (var r = 0; r < categories.length; r++) {
tr = document.createElement('tr');
row = jsonResponse["lighthouseResult"][categories[r]];
var ids = 'performance,accessibility,best-practices,seo,pwa'.split(',');
for (var i = 0; i < properties.length; i++) {
var td = document.createElement('td');
td.id = ids[i];
td.className = "score";
td.appendChild(document.createTextNode(row[properties[i]].score));
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('analysisTable').appendChild(table);
}
};
xhttp.open("GET", "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + encodeURIComponent(url) +
"&fields=lighthouseResult%2Fcategories%2F*%2Fscore&prettyPrint=false&strategy=desktop&category=performance&category=pwa&category=best-practices&category=accessibility&category=seo&key=AIzaSyDSNxhf0capOwppqlg9wZJUvzBewxf6mHU", true);
xhttp.send();
}
Part where I'm struggling with:
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);
I think you are after jsonResponse.lighthouseResult.categories.performance.score. You perform var jsonResponse = JSON.parse(data); so data is essentially text, and the JSON representation of that text is jsonResponse
I have a legacy barcode scanning application, which is used to issue items from the store. It has a combo box which has a list of all pending orders and when the user selects an order, it will list out the items expected to be issued with their quantities. Then the user presses 'f7' as a shortcut key and a new barcode field is added dynamically and then they have to scan the barcode of the bin location and after it is validated, automatically another field for the item code is added dynamically. After the item code is validated, the quantity field is added dynamically wherein the user inputs the quantity taken from that bin location. The user presses 'f7' again and the process repeats unless they finish collecting the items.
At last, they save the order and proceeds with another order.
The problem which I am facing right now is that the number of times user selects the order and presses 'f7', that number of fields are added automatically.
Example, the first time when the page loads, the user selects the order, presses 'f7', one field for bin location is added automatically, no issue here. Now, due to some reason, the user selects a second order and presses 'f7', now 2 bin location fields are added automatically. The user selects third order and presses 'f7', now 3 bin location fields are added automatically. This goes on repeating unless the user refreshes the page and starts new.
There is a variable serial defined which I have tried resetting at the time of user selecting the order but the problem still exists. I have tried resetting the variable at different places, but the problem doesn't go away.
I have used hotkeys javascript to use 'f7' as the shortcut
https://unpkg.com/hotkeys-js#3.7.1/dist/hotkeys.js
During the HTML load, a select input box is populated with all the pending orders and the below code calls the function ValueChanged with the order number when the value is changed:
<select name="Request" onchange="ValueChanged(this);;">
The function ValueChanged builds a URL with the order number and passes an Ajax request to another page through function SendAjaxRequest which collects the required data and then another function SetValues builds a table with the data on the page. Now, this function SetValues has the shortcut function hotkeys which adds the field dynamically.
Below is the javascript code
stopEvent = function(ffevent)
{
var current_window = window;
if(current_window.event) //window.event is IE, ffevent is FF
{
//IE
current_window.event.cancelBubble = true; //this stops event propagation
current_window.event.returnValue = false; //this prevents default (usually is what we want)
}
else
{
//Firefox
ffevent.stopPropagation();
ffevent.preventDefault();
};
}
function validateAllInputBoxes(ffevent)
{
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; ++i)
if(inputs[i].type === 'text')
if(inputs[i].value === '')
{
alert("form could not be sent one input text field is empty");
stopEvent(ffevent);
}
var x = document.forms["myForm"]["Request"].value;
if (x == null || x == "") {
alert("Select GRN");
stopEvent(ffevent);
}
var inputFormDiv = document.getElementsByTagName('input').length;
if (inputFormDiv<=1) {
alert("Enter atleast one BIN Information");
stopEvent(ffevent);
}
}
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
var deleteRow = function (link) {
var row = link.parentNode.parentNode;
var table = row.parentNode;
table.parentNode.removeChild(table);
}
//function deleteRow(obj) {
// var index = obj.parentNode.parentNode.rowIndex;
// var table = document.getElementById("myDynamicTable2");
// table.deleteRow(index);
//}
function addTable() {
}
function load() {
console.log("Page load finished");
}
function GetXmlHTTP() {
//first check for IE:
if (window.ActiveXObject) {
var objXML = 0;
try {
objXML = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex) {
try {
objXML = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(ex) {
alert("AJAX: your browser does not support proper XMLHTTP");
}
}
return objXML;
}
//maybe Mozilla?
if (window.XMLHttpRequest)
return new XMLHttpRequest();
//unknown browser..
alert("AJAX: unknown browser.");
return 0;
} //end function GetXmlHTTP
/*
this function send request to the given URL via
GET method.
*/
function SendAjaxRequest(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
SetValues(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest1(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues1(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest2(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues2(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function ValueChanged(oDDL)
{
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveBIN.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
rqstnumber = selectedValue;
SendAjaxRequest(strURL);
}
}
function ValueChangedDesc(oDDL)
{
var selectedValue = oDDL.value;
selectedValueBIN = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveDesc.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest1(strURL);
}
}
function ValueChangedItem(oDDL)
{
var xperia = document.forms["myForm"]["Request"].value;
//var binival = bini.value;
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveItem.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime() + "&rqn=" + xperia + "&bin=" + selectedValueBIN;
//alert(strURL);
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest2(strURL);
}
}
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(3);
}
function SetValues1(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
var txt = document.activeElement.name;
var numb = txt.match(/\d/g);
numb = numb.join("");
var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table1 = document.createElement('TABLE');
//table1.border='1';
//var tableBody2 = document.createElement('TBODY');
//table1.appendChild(tableBody2);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'ItemCode');
input.setAttribute("id", serial+'ItemCode');
//input.setAttribute("autofocus",'True');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.onkeydown = function(){ValueChangedItem(this);};
var lblt = document.createTextNode('Item Code - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
var inputs1 = document.getElementById(serial+'ItemCode');
inputs1.focus();
inputs1.focus();
//inputs1.focus();
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'ItemCode') {
// alert(inputs[1].name);
//alert('arif');
//inputs[i].focus();
//break;
// }
//
//}
serial++;
} else {
}
}
function SetValues2(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//var txt = document.activeElement.name;
//var numb = txt.match(/\d/g);
//numb = numb.join("");
//var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table3 = document.createElement('TABLE');
//table3.border='1';
//var tableBody3 = document.createElement('TBODY');
//table3.appendChild(tableBody3);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var lblt = document.createTextNode('Item Desc - '+arrData[0]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "100px";
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("value", '');
input.setAttribute("name", serial+'Qty');
input.setAttribute("id", serial+'Qty');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.setAttribute("data-parsley-type",'number');
input.onchange = setTwoNumberDecimal;
td.appendChild(lblt);
tr.appendChild(td);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var td = document.createElement('TD');
var lblt1 = document.createTextNode('Enter Quantity - ');
td.appendChild(lblt1);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//var inputs = document.getElementsByName(serial+'Qty');
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'Qty') {
// alert(inputs[1].name);
//inputs[i].focus();
//break;
// }
//
//}
var inputs2 = document.getElementById(serial+'Qty');
inputs2.focus();
inputs2.focus();
//inputs2.focus();
serial++;
} else {
}
//var allTags = document.body.getElementsByTagName('*');
//var ids = [];
//for (var tg = 0; tg< allTags.length; tg++) {
// var tag = allTags[tg];
// if (tag.id) {
// ids.push(tag.id);
// }
//}
//alert(ids);
//var oformo = document.forms["1ItemCode");
//alert (oForm0);
//var valdesc = document.getElementById("");
}
function SetValues(sRawData)
{
//window.location.reload();
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//$('myDynamicTable2, table1').remove();
$('#myDynamicTable2').closest('tr').remove();
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
//document.getElementById("myDynamicTable2").innerHTML = "<br>";
//document.getElementById("table1").innerHTML = "";
serial=1;
var myTableDiv = document.getElementById("myDynamicTable");
var p=1;
var u=0;
u=parseInt(arrData[0]);
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<u; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "80px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "120px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "50px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "70px";
td.style.wordWrap = "break-word";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
var tr = document.createElement('TR');
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
var myTableDiv1 = document.getElementById("myDynamicTable1");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var j=0; j<1; j++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Press F7 to Add');
btn.appendChild(btnt);
btn.title = "Press F7 to Add";
btn.value = arrData[p];
var bin=1;
//----------shortcut.add("F7", function() {
hotkeys('f7', function(event, handler){
// Prevent the default refresh event under WINDOWS system
event.preventDefault()
// alert(serial+"BinLocation");
myTableDiv2 = document.getElementById("myDynamicTable2");
table1 = document.createElement('TABLE');
table1.border='1';
tableBody1 = document.createElement('TBODY');
table1.appendChild(tableBody1);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
for (var j=0; j<1; j++) {
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'BinLocation');
input.setAttribute("id", serial+'BinLocation');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
//input.required = required;
input.onkeydown = function(){ValueChangedDesc(this);};
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Delete');
btn.appendChild(btnt);
btn.title = "Delete";
//shortcut.add("f4", function() {deleteRow(this) });
btn.onclick = function() {deleteRow(this)};
var lblt = document.createTextNode('Bin Location - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
bin++;
}
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
myTableDiv2.appendChild(table1);
var inputs = document.getElementById(serial+'BinLocation');
inputs.focus();
inputs.focus();
serial++;
});
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
myTableDiv1.appendChild(table);
}
}
function validateForm() {
var x = document.forms["myForm"]["Request"].value;
var e = document.forms["myForm"];
e=e.getElementsByTagName('input');
e=(e.length)+1;
if (x == null || x == "") {
alert("Select GRN");
return false;
}
if (e==2) {
alert("2Number of fields is invalid");
return false;
}
//alert(e) ; // 6
if ((e - 2) % 3 !== 0) {
alert("Number of fields is invalid");
return false;
}
}
I expect that without refreshing, any number of times the user selects the order and presses 'f7', the bin location fields should not duplicate.
Thanks in advance.
I've got this piece of code that is supposed to take the function getUserEmail() (That works perfectly) then go through every row of my Access log, and if it finds the same email take the column to the left of it, where the name is. Atm it only returns my else value, which is, if it can't find a user to the email, it just returns the email.
function getUserName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Access List");
var lastRow = sheet.getLastRow();
var userEmail = getUserEmail();
var userName = "";
for (var row = 1; row <= lastRow; row++){
var EmailRange = sheet.getRange(row, 4).getValue();
if(userEmail == EmailRange) {
var userName =+ sheet.getRange(row, 3).getValue();
return userName;
}
else if (userName == ""){
return userEmail;
}
}
}
So if anyone stumbles upon this I got it working by tweaking my first code
function getUserName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Access List");
var lastRow = sheet.getLastRow();
var userEmail = getUserEmail();
//Logger.log(userEmail);
//Logger.log(lastRow);
for (var i = 1; i <= lastRow; i++) {
//Logger.log(sheet.getRange(i,4).getValue());
if(userEmail == sheet.getRange(i,4).getValue()) {
return sheet.getRange(i, 3).getValue();
}
else if(i == lastRow) {
return userEmail;
}
}
}
Works like a charm
I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}
I have a form that takes information and outputs it in a div if its complete. If the form is not complete, output is error messages relating to the specific field which needs correcting. The error messages/output update as information is changed and the button is clicked.
Currently valid output will update as it changes, but going between valid output and error messages, the two sets of text both appear on the page, and then remain there until I refresh the page. Here's the code:
/*
Project 1 - AJAX 2015
2/14/15
Mitch Gundrum
*/
/*
Function to create input and HTML elements,
Create output nodes; output div
*/
function init() {
//Output Div
var div = document.createElement("div");
div.id = "output";
//Name
var name = document.getElementById("name").value;
name.type = "text";
//Address
var address = document.getElementById("address").value;
address.type = "text";
var city = document.getElementById("city").value;
city.type = "text";
var state = document.getElementById("state");
state.type = "text";
var index = state.selectedIndex;
var fullState = state.options[index];
var zip = document.getElementById("zip").value;
zip.type = "text";
//Email
var email = document.getElementById("email").value;
email.type = "text";
//Phone Number
var areaCode = document.getElementById("areaCode").value;
areaCode.type = "text";
var prefix = document.getElementById("prefix").value;
prefix.type = "text";
var suffix = document.getElementById("suffix").value;
suffix.type = "text";
//Gender
var gender = document.getElementsByName("gender");
var genderChoice = "";
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genderChoice += gender[i].value;
}
}
//Previous Courses
var courses = document.getElementsByName("courses");
var courseChoice = "";
for (var e = 0; e < courses.length; e++) {
if (courses[e].checked) {
courseChoice += courses[e].value + ", ";
}
}
//Call Validate form method; pass all elements
validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
//Check all elements for null
function validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
var RUN_OUTPUT = 1;
function br() {
return document.createElement('br');
}
if (name == null || name == "") {
var nameError = "Name is not valid";
var printNameError = document.createTextNode(nameError);
var nameLabel = document.getElementById("nameError");
nameLabel.appendChild(printNameError);
RUN_OUTPUT = 0;
}
if (email == null || email == "") {
var emailError = "Email is not valid";
var printEmailError = document.createTextNode(emailError);
var emailLabel = document.getElementById("emailError");
emailLabel.appendChild(printEmailError);
RUN_OUTPUT = 0;
}
if (areaCode == null || areaCode == "" || prefix == null || prefix == "" || suffix == null || suffix == "") {
var phoneError = "Area Code is not valid";
var printPhoneError = document.createTextNode(phoneError);
var phoneLabel = document.getElementById("phoneError");
phoneLabel.appendChild(printPhoneError);
RUN_OUTPUT = 0;
}
if (address == null || address == "") {
var addressError = "Address is not valid";
var printAddressError = document.createTextNode(addressError);
var addressLabel = document.getElementById("addressError");
addressLabel.appendChild(printAddressError);
RUN_OUTPUT = 0;
}
if (city == null || city == "") {
var cityError = "City is not valid";
var printCityError = document.createTextNode(cityError);
var cityLabel = document.getElementById("cityError");
cityLabel.appendChild(printCityError);
RUN_OUTPUT = 0;
}
if (fullState == null || fullState == "") {
var stateError = "State is not valid";
var printStateError = document.createTextNode(stateError);
var stateLabel = document.getElementById("stateError");
stateLabel.appendChild(printStateError);
RUN_OUTPUT = 0;
}
if (zip == null || zip == "") {
var zipError = "Zip is not valid";
var printZipError = document.createTextNode(zipError);
var zipLabel = document.getElementById("zipError");
zipLabel.appendChild(printZipError);
RUN_OUTPUT = 0;
}
if (genderChoice == null || genderChoice == "") {
var genderError = "Gender is not valid";
var printGenderError = document.createTextNode(genderError);
var genderLabel = document.getElementById("genderError");
genderLabel.appendChild(printGenderError);
RUN_OUTPUT = 0;
}
if (courseChoice == null || courseChoice == "") {
var courseError = "No Courses!";
var printCourseError = document.createTextNode(courseError);
var courseLabel = document.getElementById("courseError");
courseLabel.appendChild(printCourseError);
RUN_OUTPUT = 0;
}
if (Boolean(RUN_OUTPUT) != false) {
document.getElementsByClassName("errorField").textContent = "";
runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
}
function runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
function br() {
return document.createElement('br');
}
var printName = document.createTextNode("Name: " + name + " ");
var printEmail = document.createTextNode("Email: " + email + " ");
var printPhone = document.createTextNode("Phone: " + areaCode + "-" + prefix + "-" + suffix);
var printAddress = document.createTextNode("Address: " + address + " " + city + ", " + fullState.text + " " + zip);
var printGender = document.createTextNode("Gender: " + genderChoice);
var printCourses = document.createTextNode("Courses Taken: " + courseChoice + " ");
div.appendChild(br());
div.appendChild(printName);
div.appendChild(br());
div.appendChild(printEmail);
div.appendChild(br());
div.appendChild(printPhone);
div.appendChild(br());
div.appendChild(printAddress);
div.appendChild(br());
div.appendChild(printGender);
div.appendChild(br());
div.appendChild(printCourses);
div.appendChild(br());
var output = document.getElementById("output");
if (output) {
output.parentNode.replaceChild(div, output);
} else {
document.body.appendChild(div);
}
}
I would like for only the current accurate messages to appear, either errors or valid output, not both. My element-replacing logic seems to be off. I am not using jQuery or innerHTML for this project. Please advise.
jsFiddle