I am trying to using the JS to take user input and modify certain object attributes based on the user's input. I am storing the object's index in the select's alt attribute in order to use that to update the correct object. I'm getting an error: element[Payment_Format_name] is undefined
The WF.php file takes data from a CSV and formats it into a mulch-dimensional object.
$(document).ready(function() {
$.getJSON('WF.php', function(data) {
var newDiv, NewDiv2, NewDiv3,InvoiceInfo, count, DeliveryMethod, PaymentFormat, Payment_Format_id, Payment_Format_name;
count = 0;
$.each(data, function(index, element) {
count = count + 1;
//document.write (count);
newDiv = $('<div/>').addClass('row').appendTo('#showdata');
newDiv3 = $('<div/>').addClass('hd').appendTo(newDiv);
$('<div class="hd_field">' + element['PmtRec']['RcvrParty']['Name']['Name1'] + '</div>').appendTo(newDiv3);
if (element['PmtRec']['PmtMethod'] === 'CHK'){
$('<div class="hd_field">Delivery Method: <select alt="Delivery_Method" " id="Delivery' + count +'" class="Delivery_Method"><option value="100" selected="selected">US Mail</option><option value="300">Foreign Mail</option><option value="J00">Certified Mail with Return Receipt</option></select><div id="Selected_Method' + count +'"></div></div>').appendTo(newDiv3);
}
else if (element['PmtRec']['PmtMethod'] === 'DAC') {
$('<div class="hd_field">Payment Format: <select alt="'+index +'" id="Payment_' + count +'" class="Payment_Format"><option value="CTX" selected="selected">Company to Company</option><option value="PPD">Company to Person</option></select><div id="Selected_Format'+count+'"></div></div>').appendTo(newDiv3);
}
$('<div class="hd_field">' + 'Total: ' + element['PmtRec']['CurAmt'] + '</div>').appendTo(newDiv3);
InvoiceInfo = element['PmtRec']['PmtDetail']['InvoiceInfo'];
$.each(InvoiceInfo, function(index, element) {
newDiv2 = $('<div/>').addClass('sub_row').appendTo(newDiv);
$('<div class="field">' + element['InvoiceNum'] + '</div>').appendTo(newDiv2);
$('<div class="field">' + element['NetCurAmt'] + '</div>').appendTo(newDiv2);
});
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
//alert(Payment_Format_name);
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
console.log(data);
});
});
PHP (this is a snippet, I'm actually creating a lot more elements here)
if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$cardCodes = array();
$payments = array();
$details = array ();
while ($row = fgetcsv($handle, 1024, ",")) {
$cardCodes[] = array_combine($headers, $row);
}
$prevCode = '';
foreach ($cardCodes as $key => $value) {
$payments[$value['CardCode']]['PmtRec']['PmtCrDr'] = 'C';
$payments[$value['CardCode']]['PmtRec']['PmtFormat'] = 'CTX';
fclose($handle);
echo json_encode($payments)
Ok, so for starters,
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
is not what you want - this function is reassigned to the change event of the 'select.Payment_Fomat' element for each iteration of $.each(data, function(index, element). The event listener should be added outside the $.each function, inside the $.getJson call and it needs to loop over the elements object, and try to find the correct data to update.
Apologies for the uselessness earlier, it was 5am and apparently I was slightly delusional.
Related
<script> //script loading the csv and reading the files to out into an array of variables which are used in dropdown
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(","); //split to separate the column inside the csv
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
document.getElementById("try").innerHTML = "Value: "+ $colData; //just to check the value
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $values = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $values += $colNames[$b] + ': <input id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" value="' + $csvData[$a][$colNames[$b]] + '" /><br />';
}
document.getElementById("fields").innerHTML = $values;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
</script>
Currently I have two columns in csv and need to pick the value of one of the column item. Which is selected upon the dropdown selected by the user and then need to modify the value. The $values variable stores both the columns values.
I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);
take your time to read my explanation and ask me if i didn't explain myself well, thanks.
Don't mind how i print whith php, it it okay this way, this is a php setting.
i have in a template an input number that the client will fill with an amount of pallets, in the same template i have a table with as many tr as boxes the order has.
so, there are as many selects as tr, because it is used to assign the box to a pallet.
When the process is done i have the info in my database and if the client enters again he will need to have all the data in place, so the input number is filled and that fills all the selects with the amount of otions as the input, ok.
the fill process is made with jquery.
in the template, i have only this to make the select
<td><select class="pallets_assign" name="boxes[<?=$box;?>][which_pallet]"></select></td>
UPDATE:
to load the options in the selects i use this inside a document ready :
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
form the tamplate i call it like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
total_pallets is the id of the input number
My question is: how do i mark as selected the option which value i have stored in my database if i don't have the options created when the DOM is loaded but when that input number changed?
Thanks for your time.
Thanks to #AlonEitan to helping me find a way to solve this
in the template i had a script that did something like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
changed to:
var init = function() {
var option = [];
<? foreach ($products as $product) { ?>
<? for ($i = 1; $i <= count($product["boxes"]); $i++) { ?>
option.push(<?=(somechecks ? $product["boxes"][$i]["which_pallet"] : false);?>);
<? } ?>
<? } ?>
someone.something('#total_pallets', '.pallets_assign', option);
};
and in my js file i had this:
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
which is now:
var someone = function() {
var something = function(from_pallets, to_pallets, option) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
select.each(function(i) {
for (var j = 1; j <= qty.val(); j++) {
$(this).append('<option value="' + j + '"' + (j == option[i] ? ' selected="selected"' : '') + '>' + j + '</option>');
}
});
};
qty.on('change', update);
update();
}
});
It is a shame that in the beginning this got that many downvotes because i think is a cool way to solve this kind of issue and people will profit of this, but anyway.
I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);
I am trying to write a small javascript function which takes data from OpenSignal and then displays it in an html table.
This worked fine up until the point where I tried to make it user friendly by adding in an html form to accept the postcodes input. I tried to avoid using PHP to do this as my client won't have this installed.
I am adding an event listener to the submit button to detect when the form data has been submitted. I am then taking this and validating the string contains valid postcode(s). If they're invalid the program spits out an alert which says "Sorry but you seem to have entered an incorrect postcode.".
If not then I am taking the postcodes and passing them into my function processPostcodesOnServer(). The thing is that this doesn't work inside the event listener. When I pass postcodes in manually using javascript arrays and call the function outside of the event listener everything works fine. When I put it in the event listener it simply doesn't work. I have checked all the inputs to the function are correct and have stepped through the whole program numerous times and cannot find out what is causing the problem. It seems to me this is just another case of Javascripts random behaviour.
Can anyone help?? This is my HTML and Javascript files (I am using some JQuery so you will have to link with the latest version if you want to run this).
<!DOCTYPE html>
<html>
<head>
<title>Mobile Signals</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="NetworkStats.js"></script>
</head>
<body>
<form id="postcodeForm">
Enter postcodes separated by commas<br>
<input type="text" id="postcodes" name="postcodes">
</br></br>
<input type="submit" value="Submit" id="submitButton">
</form>
<div id="theDiv">
</div>
<div id ="secondDiv"> </div>
<table id="theTable" border="1">
</table>
And Javascript
$( document ).ready(function() {
document.getElementById('submitButton').addEventListener('click', function() {
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for (var postcode in output) {
var newPostcode = checkPostCode(output[postcode]);
if (newPostcode) {
postcodeString += " true ";
} else {
postcodeString += " false ";
}
}
if (postcodeString.indexOf("false") >= 0) {
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
} else {
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
}, false);
function processPostcodesOnServer(output) {
var apiKey = "c590c63f5b3818271a87a3e89fa215ae";
var distance = 10;
var tableNumber = 0;
//var output = ["WR141NE"];
for (var postcode in output) {
strippedPostcode = output[postcode].replace(/ /g,'');
getLatAndLong(strippedPostcode);
}
function googleCallback(latitude, longitude, postcode) {
contactServer(latitude, longitude, postcode);
}
/* Function to contact google and convert the postcode to lat long */
function getLatAndLong(postcode) {
var latitude;
var longitude;
var googleXmlHttp = new XMLHttpRequest();
var googleUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="+ postcode + "&sensor=false";
googleXmlHttp.onreadystatechange = function() {
if (googleXmlHttp.readyState == 4 && googleXmlHttp.status == 200) {
var latLong = JSON.parse(googleXmlHttp.responseText);
latitude = latLong.results[0].geometry.location.lat;
longitude = latLong.results[0].geometry.location.lng;
googleCallback(latitude, longitude, postcode);
}
}
googleXmlHttp.open("GET", googleUrl, true);
googleXmlHttp.send();
}
function contactServer(latitude, longitude, postcode) {
var xmlhttp = new XMLHttpRequest();
var networkStatsUrl = "http://api.opensignal.com/v2/networkstats.json?lat="+latitude+"&lng="+longitude+"&distance=" + distance + "&apikey=" + apiKey;
/*
Functions to contact server and read JSON response back for NetworkStats
*/
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
sortTableData(myArr, postcode);
//displayData(myArr);
}
}
xmlhttp.open("GET", networkStatsUrl, true);
xmlhttp.send();
var functionCount = -1;
function sortTableData(arr, postcode) {
tableNumber++;
$("body").append("</br>" + postcode + "</br>");
theTable = "<table id='table"+ tableNumber + "' border='1'> </table>"
$("body").append(theTable);
var column1 = new Array();
var column2 = new Array();
var column3 = new Array();
var column4 = new Array();
var column5 = new Array();
var column6 = new Array();
var column7 = new Array();
//var output = '<table border="1">';
//var output = "";
for (var obj in arr) {
// find all the networks
if ((typeof arr[obj] === 'object') && (obj == "networkRank")) {
var networks = new Object();
networks = arr[obj];
var allNetworkKeys = Object.keys(networks);
//console.log(allNetworkKeys);
var networksArray = new Array();
$.each(networks, function(networkKey, networkValue){
//Do something with your key and value.
column1.push(networkKey);
if (networkKey.substring(0, 7) == "network") {
$.each(networkValue, function(networkTypeKey, networkTypeValue){
if (networkTypeKey == "type2G") {
column2.push('');
column3.push(networkTypeKey);
for (var variable in networkTypeValue) {
column2.push(variable);
column3.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type3G") {
column4.push('');
column5.push(networkTypeKey);
for (var variable in networkTypeValue) {
column4.push(variable);
column5.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type4G") {
column6.push('');
column7.push(networkTypeKey);
for (var variable in networkTypeValue) {
column6.push(variable);
column7.push(networkTypeValue[variable]);
}
}
});
//console.log(column1);
}
//console.log(column1, column2, column3, column4);
displayTable(column1, column2, column3, column4, column5, column6, column7);
column1 = []; column2 = []; column3 = []; column4 = []; column5 = []; column6 = []; column7 = [];
});
}
}
}
var counter = 0;
function displayTable(column1, column2, column3, column4, column5, column6, column7) {
var output = ""
//console.log(counter);
counter++;
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
for (var i=0; i<highestNumber; i++) {
var column1Reference = column1[i];
var column2Reference = column2[i];
var column3Reference = column3[i];
var column4Reference = column4[i];
var column5Reference = column5[i];
var column6Reference = column6[i];
var column7Reference = column7[i];
if (column1Reference === void 0) {
column1Reference = " "
}
if (column2Reference === void 0) {
column2Reference = " "
}
if (column3Reference === void 0) {
column3Reference = " "
}
if (column4Reference === void 0) {
column4Reference = " "
}
if (column5Reference === void 0) {
column5Reference = " "
}
if (column6Reference === void 0) {
column6Reference = " "
}
if (column7Reference === void 0) {
column7Reference = " "
}
output += "<tr>";
output += "<td>" + column1Reference + "</td>";
output += "<td>" + column2Reference + "</td>";
output += "<td>" + column3Reference + "</td>";
output += "<td>" + column4Reference + "</td>";
output += "<td>" + column5Reference + "</td>";
output += "<td>" + column6Reference + "</td>";
output += "<td>" + column7Reference + "</td>";
output += "</tr>";
}
//output += "</table>";
//var table = document.getElementById('theTable');
//console.log(output);
//oldOutput = table.innerHTML;
//table.innerHTML = oldOutput + output;
$("#table" +tableNumber).append(output);
console.log(output);
}
}
}
});
Alright, I got it working.
The table would actually be displayed, if only submitting the form wouldn't reload the page.
There are two ways around this:
Change your click handler to a submit handler and cancel the event!
Replace
document.getElementById('submitButton').addEventListener('click', function() {
// ...
}, false);
by
document.getElementById('postcodeForm').addEventListener('submit', function(event) {
event.preventDefault();
// ...
}, false);
Remove the form:
That would be as simple as removing <form id="postcodeForm"> and </form> from your HTML code, but since you use $('#postcodeForm') in JS, you're gonna have to change
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
into
var output = document.getElementById('postcodes').value.split(",");
to make it work.
(Inlining postcodeString is not actually necessary, but I suggest it, see below.)
If you go with this option, I suggest also removing the name attribute from #postcodes, simply because it serves no purpose.
But regardless of which option you choose, you should fix all those </br>s: It's <br> in HTML 5 (and it was <br/> in HTML 4, but never </br>).
(And don't forget those in your JS!)
And what is the googleCallback function good for, if it only passes its arguments to a function with the exact same list of parameters? Why not use contactServer directly?
And this code is really inefficient:
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for(var postcode in output)
{
var newPostcode = checkPostCode(output[postcode]);
if(newPostcode)
{
postcodeString += " true ";
}
else
{
postcodeString += " false ";
}
}
if(postcodeString.indexOf("false") >= 0)
{
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
}
else
{
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
I mean, strings, really? Consider:
// check each postcode to see if there is any invalid postcodes
for(var postcode in output)
{
if(checkPostCode(output[postcode]) === false)
{
// current postcode is invalid so output an error message and return
window.alert("Sorry but you seem to have entered an incorrect postcode.");
return;
}
// at this point, all the postcodes are valid, proceed to perform operations on them
processPostcodesOnServer(output);
Also, you use a lot of variables only exactly once, resulting in quite an overhead.
For example, this:
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
Which could be shortened to this:
var highestNumber = Math.max(column1.length, column2.length, column3.length, column4.length, column5.length, column6.length, column7.length);
Sure this makes the line a little longer, but for 7 additional characters you can save 7 entire lines!
Or, your displayTable function could really be shortened to this:
function displayTable()
{
var output = '';
var highestNumber = Math.max(arguments[0].length, arguments[1].length, arguments[2].length, arguments[3].length, arguments[4].length, arguments[5].length, arguments[6].length);
for(var i = 0; i < highestNumber; i++)
{
output += '<tr>';
for(var j = 0; j < 7; j++)
{
output += '<td>' + arguments[j][i] + '</td>';
}
output += '</tr>';
}
$('#table' + tableNumber).append(output);
}
Then, you have a lot of {1} in your RegEx - why? [0-9]{1} is equal to [0-9] (or \d, but with that be careful to escape \ if using it in strings).
And finally, I suggest you run your code through JSHint or something similar to get rid of inconsistencies (be careful with JSLint though, that one has really aggressive and unreasonable conventions).
You have var postcodeString twice.
var keyword should only be used once per scope.