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!";
}
}
Related
I want the user to input both 'part ID' and 'quantity' through prompt and have those values added to a table; which I've managed so far. After that, I want to add another row below the first one using the same method resulting in 2 rows with different values etc.
<html>
<head>
</head>
<!--CREATE AND POPULATE TABLE -->
<body onload="partID(); qty()">
<table id="resultsTable" border=".5px" class="results">
<tr><th>Part ID</th><th>Quantity</th>
<tr>
<td id="partID">Part ID</td>
<td id="qty">Quantity</td>
</tr>
</table>
<br>
<!-- I want this f('createTable') to bring the prompt back and append to existing table onclick, if that makes sense -->
<button onclick="createTable()">Add Another Part</button>
</body>
<!-- LOCAL SCRIPTS -->
<script>
function partID(){
var partID = prompt("Enter part ID:");
var x = document.getElementById('partID');
x.innerHTML = partID;
}
function qty(){
var qty = prompt("Enter Quantity:");
var y = document.getElementById('qty');
y.innerHTML = qty;
}
</script>
</html>
I can get it to work once around but I'm not sure how to repeat it for a new row and without losing previous data.
What you want to do is append data to the table, right now you are setting the values of individual cells instead of just appending them to the already existing ones.
JavaScript has a neat little shortcut for appending (just like many other languages) which is +=, basically var myVar = 'Foo'; myVar += 'Bar'; is equal to var myVar = 'Foo'; myVar = myVar + 'Bar';
function add() {
//prompt the user with boxes for the ID and quantity
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
//generate the HTML for a new table row and insert the given values
var table_html = "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>";
//append the HTML to the already existing HTML in the table
document.getElementById('resultsTable').innerHTML += table_html;
}
/*I dont like default buttons*/
button {
background-color: lightgrey;
color: black;
padding: 8px;
border: 0px;
}
button:hover {
background-color: grey;
}
<html>
<head>
</head>
<body onload="add();">
<!-- instead of onload use a button so the user can repeat the action multiple times -->
<button onclick="add();">Add part</button>
<hr>
<table id="resultsTable" border=".5px" class="results">
<tr>
<th>Part ID</th>
<th>Quantity</th>
</tr>
</table>
<br>
</body>
</html>
I hope this helps, if you need further explanation about the code just leave a comment.
Good luck.
From what I understand, you want to be able to add a new row to the <table>. For this, you probably want to use a button.
<button onclick="addRow()">Add row</button>
Then you can add a row using insertAdjacentHTML :
function addRow() {
var table = document.getElementById('resultsTable');
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
table.insertAdjacentHTML('beforeend', "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>")
}
Using insertAdjacentHTML is safer and more efficient than replacing the whole table innerHTML.
I have an input where I enter a small natural number, e.g. 4, and then after hitting enter it creates a special square table (the dimensions are equal to the number entered by the user). After the table there is also a button (which shouldn't be too important for this toy example).
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script type="text/javascript">
function createTable(num_rows,num_cols,idString)
{
var theader = '<table class="table table-bordered table-condensed">\n';
var tbody = '';
for( var i=0; i<num_rows;i++)
{
tbody += '<tr>';
for( var j=0; j<num_cols;j++)
{
tbody += '<td><input type="text" class="form-control" /></td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById(idString).innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
Enter Number: <input type="text" name="numberCities"
onChange='createTable(this.value,this.value,"costMatrixDiv")'><br>
Table:
<div id="tableDiv"></div>
<button>I am a Dummy-Button!</button>
</body>
</html>
The Plunker version:
https://plnkr.co/edit/DWYEbllT2ynihoTreEDY?p=preview
What I want: Before entering a number, the user can see the text "Table:" as well as the Button. However, I want those parts not being present before user input.
What I don't want: I don't want to create the text "Table:" as well as the Button in one wish with the matrix through function createTable(...). This would lead to the desired solution for this toy example, but not to the ideal solution for the more complex project I am working on. It would be ideal to create a div-section around "Table:" as well as the Button and to have a technique to make the div-section appear when the user enters a number.
Thank you!
Odd toy example and hard to give a good answer without knowing what's going on otherwise and why we're writing plain JS, but:
Put <div id="tableHolder" style="display: none;"> before Table: and </div> after </button>.
Then in your onchange, you could do:
createTable(...); showHolder(this.value);
In your script:
function showHolder(value) {
var s = document.getElementById('tableHolder').style;
var newD = value%1 == 0 && value > 0 ? 'block' : 'none';
if(s.display != newD) {
s.display = newD
}
}
So the createTable function is returning:
Uncaught TypeError: Cannot set property 'innerHTML' of null
The 3rd parameter of the onChange function on your input is trying to eventually set the innerHTML of whatever is passed to it. So if you change that to tableDiv, like so:
<input type="text" name="numberCities" onChange='createTable(this.value,this.value,"tableDiv")'>
Then it works for me.
DEMO
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"]) }
);
});
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 want to create a form to add multiple images with caption . As I m php and mysql person. So if i could get new fields on clicking addmore then i can do the rest php mysql part.
How can i set var x to create a new row to provide new browse button and caption textfield.
<script type="text/javascript">
<!--
function addMore() {
if (document.getElementById && document.createElement) {
var x = ;
document.getElementById('inserthere').appendChild(x);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}
function delMore() {
if (document.getElementById && document.createElement) {
var node = document.getElementById('inserthere')
node.removeChild(node.childNodes[0]);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}
// -->
</script>
</head>
<body>
<table>
<tr><td>Select Image<input type="file" name="img[]" id="img" /></td><td>Add caption
<input type="text" name="img_cap[]" id="img_cap" /></td>
</tr>
<span id="inserthere"></span>
</table>
add More<br />
remove
</body>
Till someone replies i am going to learn , explore internet and try try try.....
It's not the prettiest way but the simplest, quickest way is probably to give the table an id property (say, for example, 'imgtable'), and do the following in your addMore() function:
var x = document.createElement('tr'); // create a new row ready to add
x.innerHTML = '<td>Select Image<input type="file" name="img[]" id="img" /></td><td>Add caption <input type="text" name="img_cap[]" id="img_cap" /></td>'; // fill it with your code
document.getElementById('imgtable').appendChild(x) // add the new row to the table
As you want to learn more though, be sure to look up methods like document.createDocumentFragment() as a way of appending individually declared elements to an object before you actually add it to the DOM. The innerHTML method I have used can be quicker but it's not as neat and can be more difficult to debug than declaring a document fragment.
Hope this helps.