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();
Related
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
I'm stuck in my code.
I am working on interactive map and I need to fly on the coordinates with a problem. How do I know when is the problem active, well I have checked the status of the data and based on the status of object I have put them in different layers of Leaflet to show it on the map. Then I have put them in little table just below the map on my page where there is elements with unique class, data-longitude and data-latitude variables that summaries how many problems we have, and where they are.
Now, this is where my problem is. I am new to JS and JQuery, so i need to know how can i access a element attributes on click, so when i click on it it will do a function flyTo() and it will store a data-longitude + data-latitude attributes to that function.
Here is a little code with some ID's.
This is how I create element in JS:
var newOption = host_name;
var uniqID = brojac;
div.innerHTML += '<td class="' + uniqID + '"value="' + newOption + '" data-longitude= "' + longitude + '" data-latitude="' + latitude + '">' + newOption + '</td>';
This is how I have created a table in HTML document:
<table id="tablic" style="width:100%">
<caption>Aktivni problemi su na sljedećim DSLAM-ovima</caption>
<tr id="red" itemprop='koordinate'></tr>
</table>
Sorry I can't put more info in it because its sensitive data so yea, hope you guys understand that.
One more thing, that "host_name", I'm getting that info from an JSON Object where I am creating markers for my map.
Hope I can get some good help with it.
With JQuery:
Add a fix class to the td element:
'<td class="tdclass ' + uniqID + '"value="' ....
Then create a clicklistener on the class:
$('.tdclass').off('click').unbind('click').click(function(e){ //unbind and off is to remove the existing click events
console.log(e);
console.log($(this).html());
console.log($(e).html());
var lat = $(this).attr('data-latitude');
var lng = $(this).attr('data-longitude');
map.flyTo([lat,lng]);
});
If I append rows to my table like this:
$('#tbody_upload').append('<tr id="' + data.originalFiles[counter].name + '"><td>' + 'Uploading...' + '</td><td></td><td></td><td></td></tr>');
how can I remove it from another event?
$('#' + this.name).remove();
that function doesn't work, also appended items don't appear in source of the page.
If you want remove the element that triggers the event to be removed (as appears from this.name) you can simply do
$(this).remove();
Maybe you should name your table and then with a selector select the body and first errase it and then append data so every time you get new data, the table deletes the old data and puts the new one.
<table id="yourtableName" border="1" class="hoverTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
var gridBody = your tr code;
$('#yourtableName tbody').empty().append(gridBody);
Initially adding the element statically like below:
<td valign="top" id="description_div">
*<table class="des_box" id="comment_div">
<tr><td class="head" id=file_comments> The function comments </td></tr>
<tr><td class="comment" id="test_point_comment_info"></td></tr>
</table>*
</td>
Dynamically adding the element as below :
$("#description_div").append(
'<table class="des_box1" id=comment_div><tr><td class="head" id=file_comments> The function comments </td></tr><tr><td class="comment" id=test_point_comment_info_' + id + '></td></tr> </table>')
Now, when I try to fetch the element by its id (that is by "comment_div") ... I am not able to retrieve the dynamically created element. But able to fetch the static element by using $("#comment_div")
I am trying to do following on the element :
$("#comment_div").show();
tried .live() ....but was not able to fetch the dynamic element.
$("#comment_div").live().show();
check box code :
<li><input type="checkbox" name="comment" />Comment</li>
actual functions where am trying to fetch the element:
$("#checkbox_div input:checkbox").click(function() {
var division = "#" + $(this).attr('name') + "_div";
$(division).show();
}
function SetCheckboxes(checkbox_data) {
//SetCookie('pre_checkbox', "1111111111111111")
var checkbox_data = GetCookie('pre_checkbox');
if (checkbox_data == null) {
SetCookie('pre_checkbox', "1111111111111111")
checkbox_data = GetCookie('pre_checkbox');
}
checkbox_array = new Array("owner", "test_time", "bp", "single_use", "num_of_test", "pause", "clearall", "clearclass", "clearmax", "closeall", "qeinbat", "m_lint","geck","header","comment","feature");
for ( i = 0; i < checkbox_data.length; i++) {
var checkbox_name = checkbox_array[i];
var value = checkbox_data[i];
var division = "#" + checkbox_name + "_div";
if (checkbox_name=="geck" || checkbox_name=="header" || checkbox_name== "comment" || checkbox_name=="feature"){
console.log("entering_loop_as_expected")
if (value == "1") {
//alert("1");
$("#checkbox_div input[name='" + checkbox_name + "']").attr("checked", "checked");
$(division).show();
} else {
$(division).hide();
}
continue;
}
Please help me out on this.
.live() is what you wanted but it has been depreciated, you now need to use .on()
$(document).on("click", "#checkbox_div input:checkbox", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
You missed the quotes, also ensure you try to access them before they are added to DOM, e.g they will not be available on DOM ready if they are added on some button click. I think you forgot to give value of id, I have made a live demo.
Live Demo
$("#checkbox_div input:checkbox").click(function() {
var division = "#" + $(this).attr('name') + "_div";
$(division).show();
});
id=1;
$("#description_div").append('<table class="des_box1" id="comment_div"><tr><td class="head" id="file_comments"> The function comments </td></tr><tr><td class="comment" id="test_point_comment_info_' + id + '"></td></tr> </table>');
Edit based on comments and fiddle being provided.
You have few problems with html in the demo
Your html starts with td instead of table
You do not enclose the ids with quotes
You are assigning same id to more then one element, instead assign a
common class and use that.
Live Demo, Problem here are not dynamic element but the wrong HTML / Script
Html
<table>
<tr>
<td valign="top" id="description_div">
<table class="des_box" id="comment_div1">
<tr>
<td class="head" id="file_comments">The function commentszz</td>
</tr>
<tr>
<td class="comment" id="test_point_comment_info"></td>
</tr>
</table>
</td>
</tr>
</table>
<div id="checkbox_div">
<input type="checkbox" name="des" />Comment
</div>
Javascript
$("#description_div").append(
'<table class="des_box" id="comment_div2"><tr><td class="head" id=file_comments> The function comments </td></tr><tr><td class="comment" id=test_point_comment_info_' + 'id' + '></td></tr> </table>');
$(document).on("click", "#checkbox_div input:checkbox", function () {
var division = "." + $(this).attr('name') + "_box";
$(division).show();
});
If you have to use same id for more than one element with is wrong you can use attribute selector. First correct the html by enclosing td within tr and table tag.
Live Demo
$(document).on("click", "#checkbox_div input:checkbox", function(){
var division = "[id=" + $(this).attr('name') + "_div]";
$(division).show();
});
What is id value in + id +, id is undefined in current context. I have put it in single quote and its working fine.
Update: You are using same id comment_div for static and dynamic content, id should be unique in DOM. Use class instead of id for multiple elements
Updated jsFiddle
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. :)