I am trying to style an HTML table row based on values in that row, but I am stuck on step 1 - styling it at all!
Here's the code I have:
<tr id="tablerow<%=j%>">
<script type="text/javascript">
document.getElementById("tablerow<%=j%>").style.backgroundColor = "red";
</script>
<%=j> is pulling a row number in from the loop that's loading the data from the Access database as it loads the table.
The table rows are not showing up as red!
Then later I am going to use some IF statements in Javascript to color the rows based on data from some of the elements:
var datecheck = new Date;
if (document.getElementById("confirmStatus<%=j%>").value=="P" && (document.getElementById("confirmYear<%=j%>").value < datecheck.getFullYear())) {
document.getElementById("tablerow<%=j%>").style.backgroundColor = "LightCoral"; }
I was able to figure it out - thanks for the help!
Have you checked your JavaScript console?
Atleast it should be document.getElementById not document.getElementByID
Your script execute too early - html not ready yet. Try
<tr id="tablerow<%=j%>">
<script type="text/javascript">
window.addEventListener('load',function(){
document.getElementByID("tablerow<%=j%>").style.backgroundColor = "red";
}
</script>
But it's ugly idea do it by js
I find it better to use custom attributes instead of string concatenation:
<tr data-dbid="<%=j%>" style="background-color:red">
<td><input class="confirmYear" /></td>
<td><input class="confirmStatus" /></td>
</tr>
Then use that when needed:
function checkRow(id) {
var _tr = document.querySelector("[data-dbid=" + id + "]"),
_confirmYear = _tr.querySelector(".confirmYear"),
_confirmStatus = _tr.querySelector(".confirmStatus");
if (_confirmYear.value === "P" && _confirmStatus.value < datecheck.getFullYear())
_tr.style.backgroundColor = "LightCoral";
}
window.addEventListener('load',function(){
[].forEach.call(
document.querySelectorAll("[data-dbid]"),
function(el) { checkRow(el.dataset["dbid"]) }
);
});
Related
I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:
<table id="country_LE_table" style = "display:none">
<tr>
<td>Japan</td>
<td>83.7</td>
</tr>
<tr>
<td>Switzerland</td>
<td>83.4</td>
</tr>
</table>
My Javascript is:
<script type="text/javascript">
function getLifeExpectancy() {
var Country = "<?php echo $Country ?>";
document.write(Country); // this gets read OK
var table = document.getElementById("country_LE_table");
var tr = table.getElementsByTagName("tr");
document.write(tr.length); document.write("<br>"); // works as expected
for (var i = 0; i < tr.length; i++) {
document.write(tr[i].innerHTML); document.write("<br>"); // works well up to here
// the following doesn't work
var td = tr[i].getElementsByTagName("td")[0];
if (td = Country) { //need td.fullHTML/value/fullText?
return tr[i].getElementsByTagName("td")[1]; // return the number
}
document.getElementById("demo").innerHTML = getLifeExpectancy();
</script>
If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.
Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
{
}
I have created a table to display my SPARQL query result in the <td>, the result does display however I want it that when the<td> (result) is clicked on it displays a message box. Right now an extra <td> is displayed at the top and it only works for that particular one. Nothing seems to happen when clicking on the actual result <td>:
My code:
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
<body>
<script type="text/javascript">
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT ?country_name
WHERE {
?country rdf:type type:Country108544813.
?country rdfs:label ?country_name.
}
"Limit 1"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
</body>
The JavaScript code I got it from an online material so still getting my head around it , the main use of it is to display the query result. So yeah answers are really appreciated and thanks for reading:)
So first off, your html is a little off... Your table is outside the tag, when it should be inside it: (note a td usually would be in a too)
<body>
<table id="results">
<tr><td class="td" onclick="myFunction()"></td></tr>
</table>
<script type="text/javascript">
....
But to your question more precisely: you have created one cell, and attached an onclick event handler to it and it only. The javascript code you grabbed actually appends new rows and cells to the table, and those don't have onclick handlers assigned.
So I'd try something like this instead:
<script type="text/javascript">
var table = $("#results");
table.on("click", "td", myFunction); // <-- magic!
var url = "http://dbpedia.org/sparql";
The "magic" line is the sweet part: it attaches the handler on the whole table, but filter the events by the "td" selector. Ideal when you are adding DOM elements dynamically...
And then you don't need to set your initial td, then one that is empty at the top of your table and clickable... Instead, just place an empty table on your page:
<body>
<table id="results"></table>
<script type="text/javascript">
....
Hope this helps!
While looking over your code you seam to only have the click event on the static
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
When you add the dynamical the is no class or onclick event. You can fix this by either adding the onclick to the td dynamically or running a script that sets all the tds in that table to have the same click event.
function getTableCell(fieldName, rowData) {
//var td = $("<td></td>");
var td = $("<td class="td" onclick="myFunction()"></td>");
var fieldData = rowData[fieldName];
//alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
td.html(fieldData["value"]);
return td;
}
or
$("#results td").click(function(){
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
}
I am using below JavaScript code to append <tr> row to <table>:
<script type="text/javascript">
function addRow() {
var filesName = 'Document Draft.png'
var newRow = "<tr><td>td Data 1</td><td><a onclick=deleteDocument(this,'" + filesName + "')>Delete</a></td></tr>";
$("#idDocList").append(newRow);
}
</script>
This code adds one tr to table.
Problem: But the issue is that filesName has one white space which is wrongly render on DOM as below:
<tr>
<td>td Data 1</td>
<td>
<a onclick="deleteDocument(this,'Document" Draft.png')"">Delete</a>
</td>
</tr>
So the onclick doesn't work because rendered HTML is
onclick="deleteDocument(this,'Document" Draft.png')
As you can see in above line, it will take ( " ) instead of white space. How to fix it?
Since you have spaces in onclick property value, you should wrap its value with, for example, "":
...<a onclick=\"deleteDocument(this,'" + filesName + "')\">...
Fiddle example.
Instead of inline JS onclick="" (which is discouraged nowdays), you can use jQuery's .on("click"):
var filesName = 'Document Draft.png';
var newRow = "<tr><td>td Data 1</td><td><a class='delete'>Delete</a></td></tr>";
$("#idDocList").append(newRow);
$('#idDocList').on('click', ".delete", function()
{
deleteDocument(this, filesName);
});
Fiddle example.
I have a id on my page that I am trying to retrieve a number from and add a value to. For instance:
<td id="qty_295518">1700</td>
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10) + quantity;
When I try and add the numbers together it come out looking like this:
17001 instead of 1701
It is just appending the 1 to the end of 1700 instead of adding it to 1700. I have tried to use parseInt, +() but to no avail. Anyone have any suggestions?
Thanks
I made a few changes from yours but they're not too different. Here's my jsfiddle, maybe it will help? I've put an alert in there to let you know that the correct value is being returned
http://jsfiddle.net/muBJd/1/
I don't know if this is the case in your actual code, but make sure that the td is wrapped in tr and table tags.
Html
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
Jquery / Javascript
var quantity = 1;
var targetQuantity = $('#qty_295518').text();
var myInteger = parseInt(targetQuantity, 10);
var addingQuantities = myInteger + quantity;
It seems that you are doing something wrong outside from jquery code, because jquery code is working fine as I wrapped the <td> inside the <tr> of <table>. something like this.
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
DEMO
Try this:
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10);
newQty += quantity;
I created an html 5 table with a single column that holds a variety of strings which are YouTube video URLs. I am able to insert strings into the table but the issue is that I am trying to use a JavaScript function to get a link(string) and insert it into my iframe YouTube player. Here is what I have:
Here is my table:
Link: <input id="link" type="link" name="link">
<button onClick="appendRow()" > Add Song </button>
<table id = "my_table" table border = "5">
<tr>
<th>Link</th>
</tr>
<tr>
<td>http://www.youtube.com/embed/evuSpI2Genw</td>
</tr>
</table>
Here is where I call my JavaScript function to insert the URL to the YouTube player:
<iframe width="888" height="420"
src="getURL()">
</iframe>
Here is my javascript function for grabbing the URL:
var counter = 0;
var songURL = "http://www.youtube.com/embed/evuSpI2Genw";
function getNextSong()
{
if(counter != 0)
{
var tbl = document.getElementById('my_table'), // table reference
songURL = tbl.rows[counter];
counter++;
return;
}
songURL = tbl.rows[0];
counter++;
return;
}
function getURL()
{
return songURL;
}
Please keep in mind that I am new to both JavaScript and HTML5.
A few things you need to consider
tbl.rows[counter] will grab the table row as an object, which will contain a collection of cells. You need to get the content of your cell using tbl.rows[counter].cells[0].innerHTML
Also you are never setting the iframe src. Give it an ID then you can access it via javascript.
Here is rough, and I do mean rough, working sample.
HTML
Link: <input id="link" type="url" name="link">
<button onClick="appendRow()" > Add Song </button><button onClick="getNextSong()" > Play Next </button>
<table id = "my_table" table border = "5">
<tr>
<th>Link</th>
</tr>
<tr>
<td>http://www.youtube.com/embed/evuSpI2Genw</td>
</tr>
</table>
<iframe width="888" height="420" id="player"
src="">
</iframe>
Javascript
var counter = 1;//The Header Row will be row 0
var songURL = "http://www.youtube.com/embed/evuSpI2Genw";
function getNextSong()
{
var tbl = document.getElementById('my_table'); // table reference
if(counter != 0)
{
songURL = tbl.rows[++counter].cells[0].innerHTML
document.getElementById('player').src=songURL;
return;
}
songURL = tbl.rows[1].cells[0].innerHTML;
counter++;
document.getElementById('player').src=songURL;
alert(songURL);
return;
}
function getURL()
{
return songURL;
}
function appendRow()
{
var tbl = document.getElementById('my_table');
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
var cell = row.insertCell(0);
cell.innerHTML = document.getElementById("link").value;
}
window.onload=function(){
document.getElementById('player').src=getURL();
};
I've made other adjustment to your script but it still could do with some tidying up.
Example: http://jsfiddle.net/HGKgn/
I think this is what you're trying to do, but only changing the src of one iframe on the page.
http://jsbin.com/orinas/2/
Works on IE9+, FF, Chrome, and Safari. Best viewed in Chrome, Safari or IE10.
I created this demo to show you what you could possibly do, while the JS is advanced, there are a lot of core concepts added in that could help you out. Not everything is commented in, because I threw it together quickly, but it is a very good demo that can help you organize your concept.
Notice as well, I do not use the table element =) I use standard elements that you would see on modern web pages today, as well as new CSS3 features.
Instead of having a table full of strings, you should store data like that on JavaScript's side in an Array []. The links array in my demo stores all the links that will show up on page load, and afterwards a user can add more links by clicking +Add and inserting a valid Youtube embed URL (something like http://youtube.com/embed/randomString).
I will be updating this answer later on.