Populating a drop down box using javascript from server side files - javascript

I have a small site that has a dropdown box which I hope I can populate from a folder on a hosted server, each item in the dropdown box should represent the file name of each file in the folder.
This is then linked to a button which will call a function load selected data into a script to visualize.
I am currently unsure about loading the file list into the application.
so far I have:
drop down list (note: using jade):
select#dataSetChoice
the function to run a script based on the contents of the drop down box:
function loadDataSet(){
var dataSet = dataSetChoice.options[dataSetChoice.selectedIndex].text;
initialize(dataSet);
}
the button event:
button(onclick='loadDataSet()') Load data
all I need to do down is populate the drop box list based on the contents of this folder:
http://localhost/data/
Edit: html directory listing as requested
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /pje40</title>
</head>
<body>
<h1>Index of /pje40</h1>
<table>
<tr>
<th valign="top">
<img src="/icons/blank.gif" alt="[ICO]">
</th>
<th>
Name
</th>
<th>
Last modified
</th>
<th>
Size
</th>
<th>
Description
</th>
</tr>
<tr>
<th colspan="5"><hr></th>
</tr>
<tr>
<td valign="top">
<img src="/icons/back.gif" alt="[PARENTDIR]">
</td>
<td>
Parent Directory
</td>
<td> </td>
<td align="right"> - </td>
<td> </td>
</tr>
<tr>
<td valign="top">
<img src="/icons/unknown.gif" alt="[ ]">
</td>
<td>
week1
</td>
<td align="right">
2013-12-06 19:28
</td>
<td align="right">119K</td>
<td> </td>
</tr>
<tr>
<td valign="top">
<img src="/icons/unknown.gif" alt="[ ]">
</td>
<td>
week2
</td>
<td align="right">
2013-12-06 19:28
</td>
<td align="right">119K</td>
<td> </td>
</tr>
<tr>
<td valign="top">
<img src="/icons/unknown.gif" alt="[ ]">
</td>
<td>
week3
</td>
<td align="right">
2013-12-06 19:28
</td>
<td align="right">119K</td>
<td> </td>
</tr>
<tr>
<th colspan="5"><hr></th>
</tr>
</table>
<address>Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6 Server at localhost Port 80</address>
</body>
</html>
Should the jquery look similar to this:
script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
var returned_html = $.trim($('http://localhost/pje40/').html());
var trs = $(returned_html).find('tr');
trs.splice(0, 2);
trs.splice(trs.length - 1, 1);
var directory_list = [];
for(var i = 0; i < trs.length; i++)
{
var tds = $(trs[i]).find('td');
directory_list.push({
"icon": $(tds[0]).find('img').attr('src'),
"name": $(tds[1]).find('a').html(),
"href": $(tds[1]).find('a').attr('href'),
"last_modified": $(tds[2]).html(),
"size": $(tds[3]).html(),
"description": $(tds[4]).html()
});
}
alert(directory_list.length);

Well here is the sketch of what can be done with your problem. I have used jQuery to somehow ease DOM traversion
// Lets say `returned_html` it what came from server
var returned_html = $.trim($('#returned_html').html());
// We need to find all TRs and drop first two and the last one
var trs = $(returned_html).find('tr');
trs.splice(0, 2);
trs.splice(trs.length - 1, 1);
// Now we should have 4 lines (with to Parent Directory one).
// Lets create list
var directory_list = [];
for(var i = 0; i < trs.length; i++)
{
var tds = $(trs[i]).find('td');
directory_list.push({
"icon": $(tds[0]).find('img').attr('src'),
"name": $(tds[1]).find('a').html(),
"href": $(tds[1]).find('a').attr('href'),
"last_modified": $(tds[2]).html(),
"size": $(tds[3]).html(),
"description": $(tds[4]).html()
});
}
You'll get in directory_list:
[
{
description: " ",
href: "/",
icon: "/icons/back.gif",
last_modified: " ",
name: "Parent Directory",
size: " - "
},
{
description: " ",
href: "week1",
icon: "/icons/unknown.gif",
last_modified: "↵ 2013-12-06 19:28↵ ",
name: "week1",
size: "119K"
},
{
description: " ",
href: "week2",
icon: "/icons/unknown.gif",
last_modified: "↵ 2013-12-06 19:28↵ ",
name: "week2",
size: "119K"
},
{
description: " ",
href: "week3",
icon: "/icons/unknown.gif",
last_modified: "↵ 2013-12-06 19:28↵ ",
name: "week3",
size: "119K"
}
]
As you can see it still needs some post processing.
Fiddle to play with.
Update
You can get directory listing with
$.get('http://localhost/pje40/', function(html) {
process_listing(html);
});
You should proccess returned data in callback because $.get() is async by default.
But you can run into cross domain request problem here. Please read about CORS.
The other way would be to create hidden iframe and load http://localhost/pje40/. Then do some thing like I've done in my first fiddle.
Needless to say that process_listing() in this case is
function process_listing(returned_html)
{
// We need to find all TRs and drop first two and the last one
var trs = $(returned_html).find('tr');
trs.splice(0, 2);
trs.splice(trs.length - 1, 1);
// Now we should have 4 lines (with to Parent Directory one).
// Lets create list
var directory_list = [];
for(var i = 0; i < trs.length; i++)
{
var tds = $(trs[i]).find('td');
directory_list.push({
"icon": $(tds[0]).find('img').attr('src'),
"name": $(tds[1]).find('a').html(),
"href": $(tds[1]).find('a').attr('href'),
"last_modified": $(tds[2]).html(),
"size": $(tds[3]).html(),
"description": $(tds[4]).html()
});
}
}

Related

How can get second item of array with x-ray

I want to get the second item in the game: ['.contenedor-numero'], array :
var site = 'http://www.laliga.es/en/';
var url = 'liga-bbva';
var address = site + url;
x(address, '#div_clasf_38_1_3 table tbody tr', [{
rank: ".posicion",
game: ['.contenedor-numero'],
score: ".contenedor-numero.puntos",
name: x(".contenedor-nombre a", {
Abbreviation: '.nombre-equipo-clasificacion-movil',
complete: '.nombre-equipo-clasificacion'
}),
}])(function(err, data) {
console.log(data);
});
the html code struct is this :
<tr class=" ">
<td class="posicion">1</td>
<td class="contenedor-flecha"></td>
<td class="contenedor-nombre">
<a href="http://www.laliga.es/en/liga-bbva/barcelona">
<span class="escudo-equipo-clasificacion">
<span class="sprite-escudos-xs barcelona"></span>
</span>
<span class="nombre-equipo-clasificacion">FC Barcelona</span>
<span class="nombre-equipo-clasificacion-movil">FCB</span>
</a>
</td>
<td class="contenedor-numero puntos">91</td>
<td class="contenedor-numero ">38</td>
<td class="contenedor-numero no-sidebar">29</td>
<td class="contenedor-numero no-sidebar">4</td>
<td class="contenedor-numero no-sidebar">5</td>
<td class="contenedor-numero no-sidebar">112</td>
<td class="contenedor-numero no-sidebar">29</td>
</tr>
I want to scraping <td> elements that has class="contenedor-numero " with value of 38. But when I use ['.contenedor-numero'][1] nothing give me!
How can I get second element of that array?
you could do this:
x(html2, 'tr', [{
rank: ".posicion",
game: ['.contenedor-numero'],
score: ".contenedor-numero.puntos",
name: x(".contenedor-nombre a", {
Abbreviation: '.nombre-equipo-clasificacion-movil',
complete: '.nombre-equipo-clasificacion'
}),
value38: 'td:nth-of-type(5)'
}])(function(err, data) {
console.log(data);
});

Grabbing data from an array using for loop to populate a table

Problem
I'm trying to iterate over an array of objects using a for loop, but instead of getting all the items in the array that I actually see when I console.log(arr[i].Sand) I get the same number eleven times in my HTML.
script.js
$(function(){
$.ajax({
url: "https://sheetsu.com/apis/fef35fba",
method: "GET",
dataType: "json",
}).then(function(spreadsheet){
// Array of objects
var arr = spreadsheet.result;
for (i = 1; i < arr.length; i++) {
console.log(arr[i].Sand); // Just the volume of sand in tonnes
var sand = arr[i].Sand // Volume of Sand in tonnes
var salt = arr[i].Salt // Volume of Salt in tonnes
var snow = arr[i].Snow // Snow Removal total in dollars
// Changes the numbers in the table
$(".sand").html(sand);
}
})
});
spreadsheet.result
index.html
<table>
<thead>
<tr>
<th class="year"></th>
<th>
<img src="img/sand-2.png" alt="" class="icons">
<p>Volume of Sand</p>
<p class="paren">(in tonnes)</p>
</th>
<th>
<img src="img/salt-3.png" alt="" class="icons">
<p>Volume of Salt</p>
<p class="paren">(in tonnes)</p>
</th>
<th>
<img src="img/snow-3.png" alt="" class="icons">
<p>Snow Removal</p>
<p class="paren">(total in dollars)</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="year">2016</th>
<td class="sand">-<span class="asterisk">*</span></td>
<td class="salt">-<span class="asterisk">*</span></td>
<td class="snow">-<span class="asterisk">*</span></td>
</tr>
<tr>
<td class="year">2015</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2014</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2013</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2012</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2011</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2010</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2009</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2008</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2007</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr class="last">
<td class="year">2006</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
</tbody>
</table>
while I was generating the code to answer this, someone changed your ajax call.
Here's the code reworked so it should help.
$(function(){
$.ajax({
url: "https://sheetsu.com/apis/fef35fba",
method: "GET",
dataType: "json",
}).then(function(spreadsheet){
// Array of objects
var arr = spreadsheet.result;
for (i =0; i < arr.length; i++) {
console.log(arr[i].Sand); // Just the volume of sand in tonnes
sand = arr[i].Sand // Volume of Sand in tonnes
salt = arr[i].Salt // Volume of Salt in tonnes
snow = arr[i].Snow // Snow Removal total in dollars
year = arr[i].Year; //We need the year to find the right row
// Changes the numbers in the table
$("tr").each(function(){
//We need to find the correct TR object.
//Remove Any spacing outside the html to make sure we don't get anything extra.
// We need to locate the ROW that has the right year so we can populate ONLY it's columns. an id or class based off year would have made this easier and less resource expensive.
if($(this).find(".year").html().trim() == year){
$(this).find(".sand").html(sand);
$(this).find(".salt").html(salt);
$(this).find(".snow").html(snow);
}
});
}
})
});
Here is a JSFiddle to show it:
https://jsfiddle.net/g6vn4Lf6/
This line:
$(".sand").html(sand);
Finds all elements with class="sand" and then sets the inner html of all of them to the value of sand. Instead you need to label each row of the table with html (eg <tr class="year-2015">), then you can select the right td element by using something like $(".year-2015 .sand").
First, you should change the key of the year in your json response to "year" instead of ""
Then you should associate that year with the tr's in some way, such as
<tr year='2016'>
Then in your for loop you can select just the .sand element that is a child of the correct tr.
$("tr[year='" + arr[i].year + "'] .sand").html(sand)
perhaps you should dynamically add a row for each of the results you receive from your ajax call like shown below:
$(document).ready(function() {
var arrayResults = [
{ Year: '2016', Sand: '123', Salt: '234', Snow: '345' },
{ Year: '2015', Sand: '222', Salt: '333', Snow: '444' },
{ Year: '2014', Sand: '555', Salt: '111', Snow: '888' },
{ Year: '2013', Sand: '121', Salt: '232', Snow: '343' },
{ Year: '2012', Sand: '454', Salt: '565', Snow: '676' }
];
for(var i = 0; i < arrayResults.length; i++) {
var newRow = '<tr>';
newRow += '<td class="year">' + arrayResults[i].Year + '</td>';
newRow += '<td class="sand">' + arrayResults[i].Sand + '</td>';
newRow += '<td class="salt">' + arrayResults[i].Salt + '</td>';
newRow += '<td class="snow">' + arrayResults[i].Snow + '</td>';
newRow += '</tr>';
$('tbody').append(newRow);
}
});
th, td {
border: 1px solid black;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr><th>year</th><th>sand</th><th>salt</th><th>snow</th></tr>
</thead>
<tbody>
</tbody>
</table>

Angular.JS Sub-Array access [& parsing a key]

It's my first time trying to build something with angular , and i find myself not able to retrieve some JSON data.
The data is retrieve from a SQL database in JSON form then passed to a template thanks to angular route :
.when('/tasks/:TaskID',{
templateUrl: 'template/task_data_template.html',
controller:"showTaskData",
controllerAs: 'STD'
})
The showTaskData is defined as follow :
angular.module('moonDive').controller('showTaskData',function($http,$routeParams){
var store = this;
store.tasks= [];
json_Url = 'api/tasks_data.php?TaskID=' + $routeParams.TaskID;
$http.get(json_Url).success(function(data){
store.tasks = data;
})});
My Data have this structure :
This is accessible from the template html by :
{{STD.tasks[1]}}
Which return the data in that "JSON" way :
{
"ActionID": "1",
"Taskref": "1",
"Ast1_1": "",
"Ast2_1": "Start EVA watch\nopen hatch\nAssist CDR",
"Ast3_1": "",
"Ast1_2": "Egress cabin to LM porch\nReceive & jetttison bag\nReceive ETB/LEC",
"Ast2_2": "Deploy CDR PLSS antenna\nHand jettison bag to CDR\nHand ETB/LEC to CDR",
"Ast3_2": "",
"Ast1_3": "Descend lander to top rung\nUnlock and deploy MESA\nLower ETB on LEC",
"Ast2_3": "Tape recorder -off\nVerify voice signals level and uitlity floo [......]"
}
So far so good, so my final purpose is to have a table with two column (ast1 , ast2) and X row for X task. I'm not really sure how to begin , but i've tried something like that :
<table class="bordered hoverable responsive-table">
<tbody>
<tr ng-repeat="boo in STD.tasks[1]">
<td style=" color: blue;" ng-if="$odd"> {{boo}}</td>
<td style="color:red" ng-if="$even"> {{boo}}</td>
</tr>
</tbody>
</table>
Well no luck it doesn't work at all, but one weird thing that prevent me to understand what's going on is that it displays all the information but in what seems to be a random order.
I'd like to delete rows with "1" ; usually i would do a ng-if="boo.NameOfTheRow" ; but here i don't really have access to this name do I ?
So my question is : How to delete the unnecessary data? And how can I arrange my data by Astr1 and 2 (for the columns) and task 1 to X (for the rows)
Thanks a lot !
PS :
The generated code should look like that :
<table>
<thead>
<td> task </td>
<td> Astr 1 </td>
<td> Astr 2 </td>
<td> Astr 3 </td>
</thead>
<tbody>
<tr>
<td> 1</td>
<td> {{STD.tasks[1].Ast1_1}} </td>
<td> {{STD.tasks[1].Ast2_1}}</td>
<td>{{STD.tasks[1].Ast3_1}} </td>
</tr>
<tr>
<td> 2</td>
<td> {{STD.tasks[1].Ast1_2}} </td>
<td> {{STD.tasks[1].Ast2_2}}</td>
<td>{{STD.tasks[1].Ast3_2}} </td>
</tr>
<tr>
<td> 3</td>
<td> {{STD.tasks[1].Ast1_3}} </td>
<td> {{STD.tasks[1].Ast2_3}}</td>
<td>{{STD.tasks[1].Ast3_3}} </td>
</tr>
....
<tr>
<td> 7</td>
<td> {{STD.tasks[1].Ast1_7}} </td>
<td> {{STD.tasks[1].Ast2_7}}</td>
<td>{{STD.tasks[1].Ast3_7}} </td>
</tr>
</tbody></table>
Thus the data should be displayed as :
If your STD.tasks is an array of entries, then you need to simply change your ng-repeat to ng-repeat="boo in STD.tasks".
You should be getting back JSON data in array form:
[
{"field":"value", "field2": "value"},
{"field":"value", "field2": "value"},
{"field":"value", "field2": "value"},
...
]
ng-repeat will want to iterate over each of those values in the array. Right now, you've pointed it to the very first item in the array, so it's repeating over each property in the object.

Displaying JavaScript Objects in an HTML Table Using WinJS

Currently I have my images and a title for them displaying like so in my Windows 8 App:
<table>
<tbody>
<tr>
<td>Image 1 Name</td>
<td>Image 2 Name</td>
<td>Image 3 Name</td>
</tr>
<tr>
<td>
<img src="/images/image1.jpg" width="125" height="125">
</td>
<td>
<img src="/images/image2.jpg" width="125" height="125">
</td>
<img src="/images/image3.jpg" width="125" height="125">
</td>
</tr>
</tbody>
</table>
However, I would like to be able to make an array of these items using JavaScript and display them via data binding with WinJS. Currently I have made the array of objects like so:
function initialize() {
var images = [
{ name: "Image 1", photo: "/images/Image1.jpg" },
{ name: "Image 2", photo: "/images/Image2.jpg" },
{ name: "Image 3", photo: "/images/Image2.jpg" },
];
var imagesList = new WinJS.Binding.List(images, { binding: true });
WinJS.Binding.processAll(null, imagesList);
};
document.addEventListener("DOMContentLoaded", initialize);
I tried altering the HTML by adding span tags within the td tags and data-win-bind to display the content, but I keep getting undefined.
Give an id to your table and then try to replace:
WinJS.Binding.processAll(null, imagesList);
with:
var myTable = document.getElementById("my-table"); //give this ID to your table
WinJS.Binding.processAll(myTable, imagesList);
this shuold attach your object to the table so that when you use a data-win-bind it knows what object to refer to.
Also I suggest you use a WinJS.UI.Repeater to create your table.
http://msdn.microsoft.com/en-us/library/windows/apps/dn301916.aspx

Remove tables from HTML using jQuery

I've got many chunks of HTML coming into my app which I have no control over. They contain tables for layout, which I want to get rid of. They can be complex and nested.
What I want is to basically extract the HTML content from the tables, so that I can inject that into other templates in the app.
I can use jQuery or plain JS only, no server side trickery.
Does anyone know of a jQuery plugin of good tip that will do the job?
Littm - I mean to extract content from the td tags essentially. I want no trace of table left in the code when it's done. Thanks!
Here's an example of the type of HTML in question. It all comes in via XHR from some ancient application so I have no control over the markup. What I want is to get rid of the tables completely, leaving just the rest of the HTML or other text content.
<table>
<tr><td colspan="4"></td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<p>Your access level: <span>Total</span></p>
</td>
<td width="5%">
<table><tr><td><b>Please note</b></td></tr></table>
</td>
<td width="45%" style="padding-left: 6px" valign="top"><p>your account</p></td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<table>
<tr>
<td align="right">Sort Code: </td>
<td align="center"><strong>22-98-21</strong></td>
</tr>
<tr>
<td align="right">Account Number: </td>
<td><strong>1234959</strong></td>
</tr>
</table>
</td>
<td width="5%"></td>
<td width="45%" style="padding-left: 6px">Your account details for</td>
</tr>
</table>
I've tried;
var data = ""
$("td").each(function(){
data += $(this).html()
});
$("article").append(data);
$("table").remove();
But var data still contains nested td tags. I'm no JS expert so I'm not sure what else to try....
Let's suppose that you have X number of tables.
In order to extract all the content information from these, you could try something like this:
// Array containing all the tables' contents
var content = [];
// For each table...
$("table").each(function() {
// Variable for a table
var tb = [];
$(this).find('tr').each(function() {
// Variable for a row
var tr = [];
$(this).find('td').each(function() {
// We push <td> 's content
tr.push($(this).html());
});
// We push the row's content
tb.push(tr);
});
// We push the table's content
content.push(tb);
});
So for instance, if we have the following 2 tables:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
<table>
<tr>
<td>r1</td>
<td>r2</td>
<td>r3</td>
</tr>
<tr>
<td>rA</td>
<td>rB</td>
</tr>
<tr>
<td>rP</td>
</tr>
</table>
The array content will be something like this:
content = [ [ [1, 2], [A] ] ] , [ [r1, r2, r3], [rA, rB], [rP] ] ]
\_______________/ \______________________________/
1st table 2nd table
and if you want to access the first table, you'll just have to access content[0] for instance.
Now, let's suppose that you have a DIV, with and id my_div, and that you want to output some table content in it.
For example, let's suppose that you only want to have the 1st table only. Then, you would do something like this:
// Note: content[0] = [[1, 2], [A]]
var to_print = "<table>";
for(var i=0; i<content[0].length; i++) {
to_print += "<tr>";
for(var j=0; j<content[0][i].length; j++)
to_print += "<td>"+ content[0][i][j] +"</td>";
to_print += "</tr>";
}
to_print += "</table>";
$("#my_div").html(to_print);
which will give you something like this:
<div id="my_div">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
</div>
Hope this helps.
Edit: You should create a recursive function to do that.
Simply create you function that gets "td"'s as a value:
function searchTexts(td) {
if (td.find("td")) {
searchTexts(td.find("td"));
}
td.each(function(){
data += $(this).html()
$(this).remove(); // remove it for avoiding duplicates
});
}
Then call it passing a jQuery object to the function.

Categories

Resources