I'm making an API call whose result is displayed in a table. Say, the columns are 'isbn', 'name of book', 'published year'. Every row would have a copy to clipboard icon that would copy the isbn value into clipboard.
To be specific, I'm unable to copy the data["isbn"] into the clipboard, when the user clicks the copy button.
What I tried to do was to obtain the data["isbn"] and store it as foo's (input id = 'foo') value. As clipboard functions work with elements like input, etc.
Code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
<script>
async function books_data{
const response = await fetch('/books');
const data = await response.json();
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
document.getElementById("foo").value = val["JobID"];
cell1.innerHTML = data["isbn"];
cell2.innerHTML = data["name"];
cell3.innerHTML = data["year"];
cell4.innerHTML = '<button class="btn" data-clipboard-target="#foo"> Copy to clipboard </button>" ';
}
</script>
<div>
<input id="foo" style="display: none">
...
...
</div>
I'm unclear where I'm going wrong. I referred these:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand, https://clipboardjs.com/
The most popular method for Copy to Clipboard is involving Document.execCommand, which seems to be deprecated.
Related
This question already has answers here:
How to make changes to HTML document permanent using Javascript?
(3 answers)
Closed 3 years ago.
I've got a really basic HTML page that simply displays a table. I'm trying the below code so that I can add a new row to the bottom of the table each time the page is loaded (even if it's the same data for now). However, each time I load the page, the bottom element keeps getting overridden with the same data. I am trying to do something like this example on W3 Schools (without the button, but the same concept).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table" style="width:70%; text-align: center;">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Row</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script>
function myFunction() {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
};
myFunction();
</script>
</body>
</html>
I've also tried replacing myFunction above with document.addEventListener("DOMContentLoaded", function(){...}, but that hasn't solved my issue either.
JavaScript will not make permanent changes in your HTML files.
This means that after you load the page, your HTML code will be displayed and then the function will be executed, adding a new row.
After you reload again, the same process will happen, and the row will be added after the end of your second HTML row.
It doesn't matter whether you use the simple method on your code or the other one you suggest (with document.addEventListener), this function is bound to be executed only once and will not add more than one row.
The issue is that your page isn't storing its data anywhere, so whenever you reload the page you're basically destroying any data you've modified and loading it from scratch again. You should use localStorage or a local database or something like that to keep track of data, and save your page's state when the function is called or on page unload.
In pseudocode:
const loadFromLocalStorage = () => {
const rows = localStorage.getItem("extra_rows") // extra_rows can be an array
for(elem in rows) {
// add to table
}
}
const saveToLocalStorage = (obj) => {
const rows = localStorage.getItem("extra_rows")
localStorage.setItem([...rows, obj])
}
const addNewRow = () => {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
const obj = {
cell1: cell1, cell2: cell2, cell3: cell3
}
saveToLocalStorage(obj)
}
const myFunction = () => {
loadFromLocalStorage()
addNewRow()
}
myFunction()
I'm attempting to creating a hyperlink within a cell of a table, but currently the hyperlink just displays as text within the table. Looking at the console I can see linkElement is getting created properly as:
text
My JS code
//Creating the table
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//creating URL elements
linkElement = document.createElement("a");
linkElement.setAttribute("href", url);
var linkText = document.createTextNode(url);
linkElement.append(linkText);
console.log(linkElement)
cell1.innerHTML = linkElement;
cell2.innerHTML = appVersion;
My HTML:
<table id="myTable">
</table>
Use cell1.append(linkElement), cell1.innerHTML is meant to be use when providing the HTML as string not an object.
Figured it out using cell1.innerHTML= ''+linkElement+'';
I have created a table in HTML using JavaScript functions insertRow() and insertCell() functions. I have assigned an id for each cell. I would like to get the value/content of the cell in JavaScript.
Following is the code used to create the table:
<HTML>
<HEAD>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = rowCount;
var cell1 = row.insertCell(0);
cell1.id = rowCount + 'a';
cell1.innerHTML = "CELL1";
var cell2 = row.insertCell(1);
cell2.id = rowCount + 'b';
cell2.innerHTML = "CELL2";
var cell3 = row.insertCell(2);
cell3.id = rowCount + 'c';
cell3.innerHTML = "CELL3";
var cell4 = row.insertCell(3);
cell4.id = rowCount + 'd';
cell4.innerHTML = "CELL4";
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<thead>
<TD>Column 1</TD>
<TD>Column 2</TD>
<TD>Column 3</TD>
<TD>Column 4</TD>
</thead>
</TABLE>
</BODY>
I have already tried out the following options:
alert(document.getElementById(1a));
Null
alert(document.getElementById(1a).value);
Error message: Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
alert(document.getElementById("dataTable").rows[rowCount].cells[0]);
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].toString());
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].value);
undefined
Here's an example of how you get the cell's value.
Given you name them serially (starting with row then a,b,c,d you should be able to access them by id as 1a or 3c. With that said, the following is working (supplemental to what you've posted):
<!-- head -->
<script>
function getVal(cellId){
var cell = document.getElementById(cellId);
document.getElementById('a').innerHTML = cell.innerHTML;
// highlight the cell for visual effect
cell.className = 'target';
setTimeout(function(){ cell.className = ''; }, 1e3);
}
</script>
<!-- /head -->
<!-- body -->
<INPUT type="text" id="q" />
<INPUT type="button" value="Get Value" onclick="getVal(document.getElementById('q').value);" />
<span id="a"></span>
<!-- /body -->
Firstly, you should know the row number.
Use document.getElementById(id) to get the content. For example, id = $rownumber + [abcd]
Table cells have no value attribute, but you can access the content via the innerHTML property or the innerText property. The differences are that the latter has somewhat more limited browser support and it gives the text content, without any tags. Example:
alert(document.getElementById('1a').innerHTML)
If this does not work (as a comment seems to say), then the problem is somewhere else. Then you should post code that actually reproduces the issue.
To access the contents of the cells with your current code you only have to address each cell by the id you gave it, then access the innerHTML atribute:
var myCell = document.getElementById('1c')
var myCellContent = myCell.innerHTML
Remember that you have the heading for each column, so your first row that actually has content will be the '1' and not the '0'.
I am able to access the cell contents using the following piece of code:
document.getElementById("dataTable").rows[rowCount].cells[0].innerHTML
I have a table with 1 row, 11 columns. Now I generated the following JavaScript code to add a new row using a Button.
The issue is, when i refresh the page, the new rows that i added using this javascript, are lost. I want them to be saved permanently in the HTML file. How can this be done?
<script>
function AddNewRow()
{
var table = document.getElementById("table1");
var row = table.insertRow(1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);
</script>
The HTML file remains on a server inaccessible to the client, but it would be perfectly possible for the browser to save the added information - either in HTML form, or as a more storage-focused format like XML/JSON. It would then need to be loaded back into Javascript and re-added to the page each time your page starts up.
Read up on the localStorage documentation at Mozilla - they could give you a general idea of storing/loading. With the innerHTML readable/writable property, hopefully you have an idea of how you could accomplish this.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage
I'm trying to create a button to put in the each row of a table to remove that row
the table row it self will be created by javascript on the runtime
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
here is my removing row function
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
my problem is when i remove a row if that row is in the middle of my table it will mess up the indexing cuz i define removerow argument when i creat each row
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); return false; />
like if i have 5 rows and and i remove row[3] i will end up with 4 rows but my last row button is still going to pass 5 to the removerow function and of course there is no row[5]
so i thought i should re index all of the rows by simply
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
var rowCount = table.rows.length;
for(i=0 , i<= rowCount ; i++){
var cell = 'cell'+i;
cell.innerHTML='<a href="" onclick="removerow('+0+'); return false; />
}
but i need to set the td id in the numeric whey so i can change their innerhtml like this
so here is my questions :
1.how can i set the attribute like id to the created td so i can get their values later? here is how i create them
var cell2 = row.insertCell(0);
2.i findout about rowIndex property which apparently returns the row index
function removerow(x)
{
alert("Row index is: " + x.rowIndex);
}
so that is going to make my job easy and i don't need to recreate all the indexes but how can i pass the clicked row 'this' to the the function ? here is how i pass the index
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); />
and also i use dreamweaver cs5 and it doesn't seems to recognize rowIndex
Then get the index dynamically and don't set it when you create it:
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl'),
rowCount = table.rows.length,
row = table.insertRow(rowCount),
cell = row.insertCell(0),
a = document.createElement('a');
a.href = '#';
a.innerHTML = 'deleterow';
a.onclick = function() {
// `this` refers to the `a` element.
removerow(this.parentNode.parentNode.rowIndex);
return false;
};
cell.appendChild(a);
cell = row.insertCell(1);
cell.innerHTML='price';
cell = row.insertCell(2);
cell.innerHTML='name';
// still needed for IE memory leak? Don't know...
table = row = cell = a = null;
};
Setting the click event handler via JavaScript is more readable anyway (well, you could also just use this.parentNode.... in the HTML string).
The code above should do what you want (if you have questions about it, just comment). Nevertheless I wanted to answer your questions:
how can i set the attribute like id to the created td so i can get their values later?
An important thing to know is that there is a difference between HTML attributes and DOM properties. These answers describe it quite well, although it is originally about jQuery (but that does not matter).
Anyway, you already know how to set the innerHTML and you can do so similar for id:
cell.id = "something";
Have a look at the DOM element reference.
but how can i pass the clicked row 'this' to the the function
I more or less showed this in the code above. Inside the event handler, this refers to the element you bound the event to. We know that it is an a element which is a child of a td element, which itself is a child of a tr element. So to get the corresponding row, we can access this.parentNode.parentNode.
For further information regarding JavaScript, have a look at the javascript tag information page. There you will find a lot of useful links to introductions about various JavaScript related topics.
Especially have a look at the articles about event handling at quirksmode.org.
Try this I hope this helps you.
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = "row_"+rowCount;
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
function removerow(i){
var table = document.getElementById('baskettbl');
table.removeChild(document.getElementById("row_"+i));
}