Get id from foreach loop javascript - javascript

After looping the delete button, I've been trying to get the id so that I can use it with the onclick function but no luck yet.
var table = "";
res.data.forEach((value, key) => {
table += "<tr>";
table += "<td>"+value.post_held+"</td>";
table += "<td>"+value.established_officer+"</td>";
table += "<td>"+value.date_of_commencement+"</td>";
table += "<td>"+value.date_of_termination+"</td>";
table += "<td><button id=career"+value.id+" class='btn btn-danger'>Delete</button></td>";
table += "</tr>";
var career = document.querySelector("#career"+value.id);
career.addEventListener("click",()=>{
alert("done")
})
});

I think maybe you forgot to add table to DOM.
You just create a string value which contain html code, but you didn't add this html code into the DOM, so you can not find this DOM element by id.
You can use insertAdjacentHTML method to add this element which you want to DOM

Related

SPFx with REACT.js - Render table with variable number of TD

I am currently working on refactoring my existing javascript into a SharePoint Framework solution with REACT. I got most parts working but I am stumped on the Render function to return html contents for a table with a variable number of columns. The number of columns is set from a web part property. How can I convert the original javascript (below) into REACT code?
var html = "<table>";
for (var i = 0; i < data.d.results.length; i++) //data is from AJAX SP REST query
{
if ((i % tdWidth) == 0 ) { html += "<tr>"; } //if this is the first column in the row
html += "<td><div>" + data.d.results[i] + "</div></td>";
if ((i % tdWidth) == (tdWidth - 1) ) { html += "</tr>"; } //if this is the last column in the row
}
html += "</table>";
$("#tableContainerDiv").html(html); //Set the html tag of the container div
You have to create your own component to use. Check the below link.
http://buildwithreact.com/tutorial/components
OR
best thing in react is reuse the ready made component. instead of making the html from js try to use the react-super-responsive-table.
https://www.npmjs.com/package/react-super-responsive-table
You can easily loop through rows and count with headers. I hope it may help you.
OR
Another approach is to set the response into array i.e. data.d.results put in array and render your control inside the render method.
MyrenderItems = this.state.UserArray.map(function (item, i) {
.....
}

Write HTML to screen with Javascript function

I'm very new to JavaScript and HTML I and need some help!
I'm trying to write a table in JavaScript, that writes into the page HTML, and then importing that function to a HTML file to show the table.
I have this in a JavaScript file
function createTable()
{
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
document.write(table);
}
And then I specify the src and call the function in a html file like so:
<head>
<script scr = "source/file.js" type=text/javascript"></script>
</head>
<body>
<script>
createTable()
</script>
</body>
Although this works, I've heard that using document.write() is a very bad practice.
I have tried using table = document.getElementById('tablePrint').innerHTML; and then in the HTML file used <div id="tablePrint"></div> however my table doesn't show. I've also tried document.body.appendChild(table); but that doesn't work either.
Is using document.write() ok? Or is their a better way to write my table to the HTML on screen.
You are missing some double quotes in your example. I'd suggest you to use JQuery:
$(function() { // After the HTML content loads
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
$('body').append(table); // Appends HTML to an element
});
Here is the fiddle.
And here is why document.write() is not a good practice
The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Hope it helped :)
The HTML <center> element is obsolete since 1999 when HTML 4 came out. It's abolutely amazing that people (amateurs?) are still trying to use it. Let me cite from the Mozilla article:
This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the CSS text-align property, which can be applied to the <div> element or to an individual <p>. For centering blocks, use other CSS properties like margin-left and margin-right and set them to auto (or set margin to 0 auto).
Normally, we don't use document.write for creating HTML content since it does not allow to control where the content is inserted. Rather, we use suitable DOM attributes (such as innerHTML) and methods (such as appendChild).
The proper way of creating an HTML table and inserting it into the HTML body element is using the DOM methods insertRow and insertCell, as in the following code example:
function createTable() {
var i=0, rowEl=null,
tableEl = document.createElement("table");
// create 10 table rows, each with two cells
for (i=1; i <= 10; i++) {
rowEl = tableEl.insertRow(); // DOM method for creating table rows
rowEl.insertCell().textContent = "table cell "+ i +"-1" ;
rowEl.insertCell().textContent = "table cell "+ i +"-2" ;
}
document.body.appendChild( tableEl);
}
The document.write() method for this purpose is not preferred. The most preferred way to do this with pure JavaScript is to use the appendChild() method.
Try this :
var table = document.createElement("table"); //Creating the <table> element
var tr1 = document.createElement("tr"); //Creating the first <tr> element
var tr2 = document.createElement("tr"); //Creating the second <tr> element
var th = document.createElement("th"); //Creating a <th> element
var td = document.createElement("td"); //Creating a <td> element
var text1 = document.createTextNode("Title"); //Creating the content of <th>
var text2 = document.createTextNode("data"); //Creating the content of <Ttd element
document.body.appendChild(table); //The <body> is adopting the <table>
table.appendChild(tr1); //The <table> is adopting the first <tr>
tr1.appendChild(th); //The first <tr> is adopting the <th>
table.appendChild(tr2); //The <table> is adopting the second <tr>
tr2.appendChild(td); //The second <tr> is adopting the <td>
th.appendChild(text1); //<th> is adopting its content
td.appendChild(text2); //<td> is adopting its content
<center> tag is deprecated now, don't use it, use CSS instead.
Working demo
Have your function return the table as a string.
function createTable()
{
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
return table;
}
Assuming you don't want to overwrite the body completely create a div have it styled the way you want and just add the table content there.
<body>
<div id="table"></div>
<script>
var table=createTable();
document.getElementById("table").innerHTML=table;
</script>
</body>

Show/Hide Multiple DIVs in a variable

I am using nested for loops to generate multiple instances of a table with details of projects; under which I wish to have a show/hide button that will give a short description of each project at a high level.
I am tring to manipulate code I found here: https://forums.digitalpoint.com/threads/javascript-to-show-hide-tables.1009918/
The following code produces a "Show/Hide" link that does not work on my page (see screenshot). Am I missing something?
FYI - "Separate" in the code below is an array containing unique project references to facilitate the separation of the tables per project. So where Separate contains 4 elements, there should be 4 projects, 4 tables, and so on.
Many Thanks,
Karl
function showhide(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none"){
obj.style.display = "";
} else {
obj.style.display = "none";
}
}
}
for(i in Separate){
DescID[i] = "DescID"+i;}
var Table = "";
for(i in Separate){
Table += "<table id='dashboard' summary='Project Dashboard'>";
Table += "<THEAD>";
Table += "<TR><TH scope='col' colspan=4><B>"+ Separate[i] +"</B></TH></TR>";
Table += "<TR><TH scope='col'>Task Names</TH><TH scope='col'>Task Summary</TH><TH scope='col'>RAG</TH><TH scope='col'>Timeline</TH></TR></THEAD>";
Table += "</THEAD>";
Table += "<TBODY>";
for(j in Project){
if(Project[j] == Separate[i]){
Table += "<TR><TD title='" + Comments[j] + "'>"+ Task[j] +"</TD><TD>"+ Summary[j] +"</TD><TD><img src='/images/RAG/" + RAG[j] + "'></TD><TD>"+ DateType[j] +" "+ Status[j].substring(0,10) +"</TD></TR>";
}
}
Table += "</TBODY>";
Table += "</table>";
Table += "<a onclick ='javascript:ShowHide('" + DescID[i] + "')' href='javascript:;' >Show/Hide Project Description</a>";
Table += "<div class='mid' id='" + DescID[i] + "' style='DISPLAY: none' >Placeholder for Project Description</div>";
Table += "<BR>";
}
You're missing the fact that HTML tag "id"s (e.g., for your Projects' tables) should be unique, otherwise "getElementById" won't work. Now they're all set to "dashboard". At the very least you could add the index, and make them "dashboard1", "dashboard2", etc...
Also, IIRC, a better opposite for 'display = "none";' is 'display = "inline";', instead of 'display = "";'. Although this needs more testing on different browsers to select the best option.
Thirdly, your JavaScript call within the onclick events use single quotes BOTH for the attribute value definition (surrounding the JS call) and for the string parameter (the id to show/hide)... That's not valid syntax, and you need one of these two use-cases to be double-quotes.
And the other main problem your code has is as mikez302 already spotted: "Javascript function names are case-sensitive. Your function is called showhide but you are trying to call ShowHide." Correcting these two issues (the quotes and the function name) will allow the code to work, i've just tested it. :)

Remove table from <div> tag

I have a <div> tag in which I add <table> dynamically through Javascript:
var htmlText = "<table id='table_" + id + "'><tbody>";
htmlText += "<tr> <td><img src='../../Icons/action_delete.gif' onclick='javascript:RemoveUser(\"" + id + "\");' /></td> <td>" + name + " </td></tr>";
htmlText += "</tbody></table>";
document.getElementById("divSearchUsers").innerHTML += htmlText;
I add multiple table to the div. Now I want to remove a particular table.
I get the ID of the table in RemoveUser function. How do I proceed for it?
with relation to non jQuery:
Remove dom element without knowing its parent?
function removeElement(el) {
el.parentNode.removeChild(el);
}
Get the element id and use remove()
$("#table_id").remove();
if you want to remove the inner html then you should just do something like that:
document.getElementById('table_' + id).innerHTML = "";
Since id of html element is supposed to be unique, you can directly delete it using remove methos.
With jQuery
$('#tableIdToRemove').remove();
With Javascript
tableIdToRemove = document.getElementById("tableIdToRemove");
tableIdToRemove.parentNode.removeChild(tableIdToRemove);
or
If you have html and there is chance of duplicate ID out side the parent table then you can access the table to delete in relation to its parent table as follow.
$("#divSearchUsers").find('#tableIdToRemove').remove();

Parsing content in array

I would need to get only the text from certain array. So I need to parse it. I have the following code:
for(var x=0;x<contentArray.length;x++){
markup += '<td>'+contentArray[x+1] +'</td>';
x++;
}
Which gives the following output:
<td><c><ul><li>The content text</li></ul></c></td>
And it loks on browser like this:
<ul><li>The content text</li></ul>
Now I would like to get only the text (The content text& in this case). How am I able to do tit?
You can use this function to unescape HTML (stolen from the Prototype source code):
function unescapeHTML(html) {
return html
.replace(/</g,'<')
.replace(/>/g,'>')
.replace(/&/g,'&');
}
You can then use jQuery's parsing capability to get the text from the tags:
for(var x=0;x<contentArray.length;x++){
var $el = $(unescapeHTML(contentArray[x+1])).find('li'); //use the unescaped HTML to construct a jQuery object and find the li tag within it
markup += '<td>' + $el.text() + '</td>'; // get the text from the jQuery object and insert it into the fragment
x++;
}

Categories

Resources