How to fetch the dynamically created element by its ID in jQuery - javascript

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

Related

Javascript - img onlick() function passing arguments error [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I'm trying to pass arguments to onclick handler. The table rows are constructed dynamically in a loop and each row contains a tag with different args. Suppose there are two rows, and when clicking the first img, the argument is always the argument corresponding to the second(last) row.
JS code
for(...){
id = get_id(); // every row's id is different
img = '<img src="/img/icon-view.png" height="20" width="20" style="cursor:pointer"
onclick="view_detail(id)">'
row = ('<tr> ' + '<td>' + img + '</td>' + '</tr>')
$("#table_1").append(row)
}
function view_detail(id){
...
// the first row's id is always the second id's row
}
Comment:
Jquery passing ID from <img> to function gives a solution, but the trick here is id is a variable.
<img onclick="Myfunction(this.id)" src="files/pic/Website.png" id="Website">
Finally I found a workaround which is very simple - create img element and converts to string, and then put the string in row tag.
Sample code:
var img = document.createElement("img")
img.setAttribute("id","local_variable")
img.setAttribute("onclick","view_detail(this.id)")
var img_str = img.outerHTML(img)
row = '<tr>' + '<td>' + img_str + '</td>' + '</tr>'
Code in onXXX attributes is executed in the global scope, so it can't use captured local variables in a closure.
Nurul Huda's answer is ideal. But a simple fix to your code is to substitute the actual value of id rather than referencing the variable.
id = get_id(); // every row's id is different
img = `<img src="/img/icon-view.png" height="20" width="20" style="cursor:pointer"
onclick="view_detail(${id})">`
Dont use string to build DOM, but use document.createElement() instead. Then you can get instance of each target, add any event listeners, you can also pass those instances as arguments to other function as you want.
Here is a sample snippet you can try (I used button instead of img).
const tbody = document.querySelector('table tbody')
const btnAddRow = document.querySelector('button#btn-add-row')
btnAddRow.addEventListener('click', e => {
const row = document.createElement('tr')
const col = document.createElement('td')
const content = document.createElement('button')
content.innerHTML = `Row ${tbody.childNodes.length}`
content.addEventListener('click', e => {
alert(`${content.innerHTML} clicked!`)
})
col.append(content)
row.append(col)
tbody.append(row)
})
<button id="btn-add-row">Add row</button>
<hr>
<table border="1">
<thead>
<tr>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Another advantage is, your code becomes more readable and modern.

Pass php variable through JavaScript to another php page

I want to pass the id to the next page on clicking the entire row.
I tried to do it myself but I wasn't able to do so .
my code is below :
$( "#tablerow" ).click(function() {
var jobvalue=$("#jobid").val();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="tablerow">
<td><?=$srno?></td>
<td id="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
val() method works for form elements like input, select etc.
Use text() method,
var jobvalue = $("#jobid").text();
Update
An HTML can have only one ID throughout the document. To enable click event for multiple elements and pass the one that is clicked onto another page, change ID attribute to class.
<table>
<tbody>
<tr class="tablerow" >
<td><?=$srno?></td>
<td class="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
Then you can get the once clicked in JS as follows,
$( ".tablerow" ).click(function() {
/** $(this) will refer to current tablerow clicked
* .find(".jobid") will find element with class `jobid`
* inside currently clicked tablerow
*/
var jobvalue = $(this).find(".jobid").text();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});

How to apply a CSS class to an ID that just succeed

I'm working on an editable table with HTML5 attribute called contenteditable. Everything works well until I have another idea of telling user which cell is just updated. By highlight it with a class from bootstrap called alert-danger.
After a cell is successfully sent. A data is sent back to a parent page telling the result div what the status is. It only shows the status on top of the table but I'd like to add another class in the cell. So I added $("td[id="+cols3_key+"").addClass('alert-danger'); when a data calls back. Expecting the latest cell is apply with alert-danger class. But it doesn't work. Here's my script.
javascript
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var cols3_key = $(this).attr("id") ;
var value = $(this).text() ;
$.post('inc/ajax.php' , cols3_key + "=" + value, function(data){
if(data != ''){
$("td[id="+cols3_key+"]").addClass('alert-danger');
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
}
});
});
The question is : How can I change this line to refer to a cell that has been just processed?
$("td[id="+cols3_key+"").addClass('alert-danger');
Regards,
Try this, you are missing to close the ]
$('td[id="+cols3_key+"]').addClass('alert-danger');
OR
$('td[id$="cols3_key"]').addClass('alert-danger');
You can just do $(this).addClass('alert-danger'); in place of $("td[id="+cols3_key+"").addClass('alert-danger');
In case you do not get proper $(this) inside post callback, you can try $("td#"+cols3_key+"").addClass('alert-danger');
In jquery to access ID you have to use
#. For e.g, to access <td id='test'></td>
you will have to write $('td#test').addClass('newClass');
You were missing a ], so you could use $("td[id="+cols3_key+"]") which can be made simply: $("#"+cols3_key)
Note the first fix here only requires extra single quotes if the id contains special characters:
e.g. $("td[id='"+cols3_key+"']")
The second one shown will work in either case.
Instead I would suggest a better way of doing this:
1) Put your ajax call in a function so you can pass specific elements to it that will be remembered per Ajax call.
2) Just reference the element and stop worrying about the id
Something like this:
var update = function($element){
var value = $element.text();
$.post('inc/ajax.php' , $element.attr('id') + "=" + value, function(data){
if(data != ''){
$element.addClass('alert-danger');
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
}
});
}
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
update($(this));
});
Finally,
I've got my way out of here with many helps from you guys and THE notice from #TrueBlueAussie. Here's the full script.
HTML
<h2 class="lead text-danger">HTML5 Inline Edit</h2>
<div id="status"></div>
<table class="table table-bordered table-striped">
<tr>
<td id="table_col1:1" contenteditable="true">
content1
</td>
<td id="table_col1:2" contenteditable="true">
content2
</td>
<td id="table_col1:3" contenteditable="true">
content3
</td>
</tr>
</table>
CSS
#status{
background:#ff0000;
border:solid 1px #ccc;
border-radius:5px;
color:#fff;
display:none;
padding:5px;
width:100%;
}
Javascript
$(window).load(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var cols3_key = $(this).attr("id") ;
var value = $(this).text() ;
$.post('' , cols3_key + "=" + value, function(data){
if(data != ''){
$('td[id="'+cols3_key+'"]').addClass('alert-danger');//this is the trick. I need a couple of single quotes here to express that I need a var not an id name
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
setTimeout(function(){$('td[id="'+cols3_key+'"]').removeClass('alert-danger')},3000);
}
});
});
});
A working demo here - http://jsfiddle.net/nobuts/Lroqpk7x/9/

jQuery how to remove dynamically appended rows?

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);

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();

Categories

Resources