I have a webpage, which has a number of ASP.NET tables.
The tables are defined on the server as follows (id is unique for every table):
dim tblOutput as table
tblOutput.ID = id
I am trying to loop through all the tables on the webpage using JavaScript on the client as follows:
var trs = document.getElementsByTagName("table");
for (var i = 0; i < trs.length; i++) {
var res2 = trs[i].attributes("id")
alert(res2[i].id)
}
The alert always prints 'undefined'. I have debugged using firefox and id is always empty (""). What am I doing wrong?
var res2 = trs[i].attributes("id")
alert(res2[i].id)
You assign a single string to res2 and then you use res2 like it's an array in your alert. You then try and get the id from a string? Not sure what you're trying to do there... Additionally, attributes is not a function, you can access the id with .id.
var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; ++i) {
var id = tables[i].id;
alert(id);
}
Related
I'm trying to create a greasemonkey script to copy the innerHTML of some <li> elements, but I'm unable to to so because it is a nodelist.
var list = document.querySelectorAll(".bx li");
GM_setClipboard(list.innerHTML)
Iterate and generate the combined result.
var list = document.querySelectorAll(".bx li");
GM_setClipboard(
// convert nodelist to array
// for older browser use [].slice.call(list)
Array.from(list)
// iterate and get HTML content
.map(function(e) {
return e.innerHTML;
})
// combine the HTML contents
.join('')
)
Alternatively, we can use simply for loop which would be better since we don't need to create an extra array.
var list = document.querySelectorAll(".bx li");
// initialize string variable for HTML
var html = '';
// iterate over the nodelist using for loop
for (var i = 0; i < list.length; i++) {
// append the HTML content to the string variable
html += list[i].innerHTML;
}
GM_setClipboard(html);
You need to walk through the list and compose required HTML string:
var list = document.querySelectorAll(".bx li");
var html = "";
for(var n = 0; n < list.length; ++n)
html += list[n].outerHTML;
I've researched quite a bit on here and I can't seem to find something that will work for me. What I have is an application that I'm trying to have go out and return the next four bus arrival times for a bus stop. I am reaching out to an API that returns this data in a JSON file. The problem I am having is I can see my request go out via fiddler but I can't seem to get the data into an array. Below is the code that I'm dealing with right now. I'm trying to get the returned data into a table format which you can see I'm failing at.
Eventually I want to get a popup to appear when the user clicks on the Show me the next 4 bus arrival times but this was for testing purposes. I would love to have the users click on my button which calls this function and then something like a like table open with these values. If you can help with that within this code I would appreciate it as well.
JSON Data:
[{"ARRIVAL":"01:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"01:53P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:53P","ROUTE":"208","DIR":"E"}]
Code:
<script>
function getTimes(stopNumber) {
var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber ";
$.getJSON(busArrivalAPI, function(busArrivals) {
var a = [];
for (var i = 0; i < busArrivals.length; i++) {
a[i] = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
document.getElementById("results").createElement("TR");
for (var b = 0; b < 3; b++) {
var x = document.createElement("TH");
var z = a[i][b];
var t = document.createTextNode(z);
x.appendChild(t);
document.getElementById('results').appendChild(x);
};
};
});
</script>
My DIV:
<div style="overflow-x:scroll; overflow-y:scroll;" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="title:'Bus Arrival Times', selected:true">
<table id = 'results'>
<tr>
<th>Route</th>
<th>Arrival Time</th>
<th>Direction</th>
</tr>
</table>
</div>
UPDATE: Ok, I've use the makeTable idea provide below and it works when I program as seen below hard coding the json data. However, when trying to use the $.getJSON I'm having some cross domain issues now and don't know how I can get my $.getJSON request working. Any input on how to get the data from my getJSON request work be great.
function getTimes(stopNumber) {
// This is the API address I need to hit. Trying to figure out how to incorporate that and remove the function getJSON where I have the data hard coded.
//var busArrivalAPI = "http://-----/rtcTimes/"+ stopNumber + "?jsoncallback=?";
function makeTable(busArrivals) {
// This will remove old values so table will only load current Times
var results = document.getElementById("results");
var rowCount = results.rows.length;
for (var x=rowCount-1; x>0; x--) {
results.deleteRow(x);
}
// This will populate the result table with the correct bus routes/times/direction
busArrivals.forEach(function(busArrival) {
var tr = document.createElement('tr');
var route = document.createElement('td');
route.appendChild(document.createTextNode(busArrival.ROUTE));
var arrival = document.createElement('td');
arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
var direction = document.createElement('td');
direction.appendChild(document.createTextNode(busArrival.DIR));
tr.appendChild(route);
tr.appendChild(arrival);
tr.appendChild(direction);
document.getElementById('results').appendChild(tr);
});
}
function getJSON(callback) {
var data = [{"ARRIVAL":"05:23P","ROUTE":"201","DIR":"E"},
{"ARRIVAL":"05:54P","ROUTE":"202","DIR":"E"},
{"ARRIVAL":"06:33P","ROUTE":"203","DIR":"E"},
{"ARRIVAL":"07:11P","ROUTE":"204","DIR":"E"}];
callback(data);
}
getJSON(makeTable);
};
I think you could write a separate function to build the table, like this:
function makeTable(busArrivals) {
busArrivals.forEach(function(busArrival) {
var tr = document.createElement('tr');
var route = document.createElement('td');
route.appendChild(document.createTextNode(busArrival.ROUTE));
var arrival = document.createElement('td');
arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
var direction = document.createElement('td');
direction.appendChild(document.createTextNode(busArrival.DIR));
tr.appendChild(route);
tr.appendChild(arrival);
tr.appendChild(direction);
document.getElementById('results').appendChild(tr);
});
}
var busArrivalAPI = 'http://blahblahblah/rtcTimes/'+ stopNumber;
$.getJSON(busArrivalAPI, makeTable);
In each iteration of the forEach loop, you construct a tr element, insert the tds and finally put the whole thing inside the DOM.
You're creating a TR element, but never appending it to the table. Instead, you're appending the TH elements directly to the table, which is invalid.
function getTimes(stopNumber) {
var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber;
$.getJSON(busArrivalAPI, function(busArrivals) {
var table = document.getElementById('results');
for (var i = 0; i < busArrivals.length; i++) {
var a = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
var row = document.createElement("TR");
for (var b = 0; b < 3; b++) {
var x = document.createElement("TH");
var z = a[b];
var t = document.createTextNode(z);
x.appendChild(t);
row.appendChild(x);
};
table.appendChild(row);
};
});
}
I'm not sure why you need the a array. If you just want to change get the object properties into an array so you can iterate over it, you can do that with a 1-dimensional array, you don't need to save all the other rows in a 2-dimensional array. I've changed a to a single array.
when i try to place an unorderd list fetched from the database column, into a dynamically created row of a table(using createElement) it shows the list tags along with the data. but doesn't appear formatted.
here is the code
var table1 = document.getElementById('pc');
for (var x = 1; x < len; x++) {
var vals = result[x];
var row = document.createElement('tr');
row.textContent = vals;
table.appendChild(row);
}
result is from ajax and it has the lists.
By "it shows the list tags along with the data" do you mean it is actually showing the <li> tag instead of actually making a list item?
It might be storing it in your database as < instead of <.
How do you write a function/ listener in javascript that can fire when html updates?
html page is limited to the last 100 records
html page continuously adds new records (nodes)
I need to...
push the values into an array or increment a variable to sum the values
display the running total in html
Trying to create a counter that adds new values to the sum.
I believe the code below only executes once.
window.onload = function() {
var data = document.getElementsByTagName('span');
var len = data.length;
var total = 0;
var searchValue = "value";
for (var i = 0; i < len; ++i) {
var styles = data[i].getAttribute('style');
if (styles == searchValue) {
var txt = data[i].innerHTML;
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
};
Yes you can do this with just JavaScript, and a little HTML/CSS for displaying the number.
Note that it requires a fair deal of experience to manage an addon with cross-origin requests, and to show it to the user.
I am trying to access table cells in javascript using the getElementsByTagName method as shown below. Ultimately I want to compare each cell in the array to another value, and be able to change the background color of that cell according to the comparison.
var cells = document.getElementById("myTable").getElementsByTagName("tr");
for (i = 0; i < cells.length; i++)
{
cells[i] = cells[i].getElementsByTagName("td");
}
However, if I try to access cells[0][0], it returns undefined. I feel like I don't fully understand getElementsByTagName is doing... is there any hope for this method? Is there a more efficient one?
use jquery it will be simple :
var contentArray = new Array();
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});
You can access any cell directly using the table element's .rows property, and the tr element's .cells property:
var myCell = myTable.rows[y].cells[x];
No need to build your own array.
So don't use .getElementsByTagName(), which returns a one-dimensional array. (Well, actually a NodeList, but you can use it like an array as long as you remember that it is live.)
If you did want to loop through all cells to compare them to some other value here's how, left to right, top to bottom using .rows and .cells:
var rows = document.getElementById("myTable").rows;
for (var y=0; y < rows.length; y++) {
for (var x=0; x < rows[y].length; x++) {
var cellAtXY = rows[y].cells[x];
cellAtXY.someProperty = something; // your code here
}
}
You need to do something like this for each row.
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
then build your array from the contents of these variables.
Use this to get the table cells as 2D array
var tableRows = (document.getElementById("myTable")).getElementsByTagName("tr");
var cells = [];
for(var i = 0; i < tableRows.length; i++) {
cells.push(tableRows[i].getElementsByTagName("td"));
}
And now you can get any cell on your table using
cells[0][0]