JQuery appending elements and acces to appended elements - javascript

I have a code where i appending to div some html over JQuery like
$("#divId").append("<div class='click' data-id='id'></div>");
and I want to acces by click appended div like this
$(".click").click(function(){
var id = $(this).attr('data-id');
alert(id);
});
but when I click, nothink happens, is there some solution for this? Thanks!

You need to use event Delegation.
$("body").on('click', '.click', function(){
var id = $(this).attr('data-id');
alert(id);
});
As the events are only bound for already existing elements on the page. but in your case you are dynamically appending the elements.
body can also be substituted to the closest ancestor that contains these elements.
$("#divId").on('click',
Check Fiddle

Related

How do you target an element that is dynamically generated? [duplicate]

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.
Thanks!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
$('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});
$('#approve').on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:
$('#yourContainer').on('click', '#approve', function(){
//your code here..
});
Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should
bind .on() with $(document) selector. This will always contain your dynamically added elements.
$(document).on( eventName, selector, function(){} );
$(document).on('click','#approve',function(){
//your code here
});
I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:
// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');
// This won't work...
$("#mynewthing")...
// But this will...
$(document.getElementById("mynewthing"))...
This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.
Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var $button = $('<button style ="button" id="approve">Approve</button>');
$button.on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
$('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});
Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.
A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var id = snapshot.name();
var $button = $('<button style="button">Approve</button>');
$button.on("click", function(){
// use parent.closest(...) in place of an ID here!
var text = $(this).parent().closest('textarea').val();
postsRef.push({'text':text});
$(this).parent().remove();
});
/* just an example of how to use a data-* tag; I could now refer to this element using:
$('#feed').find('[data-record="'+id+'"]') if I needed to find it */
$('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});
I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.
$("#button").click(function(e){
$(".parentContainer").find(".dynamically-child-element").html("Hello world");
});
Or
$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event
So this is my demo

Get any element tagName on click

I need to take $('this') information from any element i click on the document.
I tried the following code:
$('body').click(function(){
var element = this.tagName; // or var element = $(this).prop('tagName');
alert(element);
});
The problem is that wherever i click i get only BODY element. If i click on a button or a div i want to get that element. How can i create something general to take every element i click ?
Because you are attaching your event handler to the body element, this will always be the body. Instead, interrogate the event.target property:
$('body').click(function(e){
var element = e.target.tagName;
alert(element);
});
Example fiddle
nodeName
$('body').click(function(e){
alert(e.target.nodeName);
});
http://quirksmode.org/dom/core/#t23
My advice is not to use tagName at all. nodeName contains all
functionalities of tagName, plus a few more. Therefore nodeName is
always the better choice.
it also looks like the performance is slightly better on some versions of chrome and firefox.
http://jsperf.com/tagname-vs-nodename/2
this always refers to the element where the event handler is assigned, not where the event originated (well, you can change it, but it's pretty unusual to do so). For that, you need Event.target:
$('body').click(function(event){
var element = event.target.tagName; // or var element = $(this).prop('tagName');
alert(element);
});

Jquery appending without removing

So I need to grab content from a specific class and put it in a div, which I use append for...my issue is that append removes the item I append, and I need it to stay there, Here is my code:
$(document).ready(function(){
var $content = $('#popupcontent');
var $window = $('#popupwindow');
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a);
$window.fadeIn(300);
});
$('.close').click(function(){
//alert('running');
var a = $content.contents('span');
$window.fadeOut(300);
$('#popupcontent span').remove();
});
});
So how can I get the content, when clicked, from each .open span to the #popupcontents id without removing it from the .open class?
To show you what I mean: JSFIDDLE
NOTE: the second time you click a link, it wont append any content because that content has been removed from that class, which is not what I want
NOTE2: I cannot simply just append instead of remove in the $('.close').click function because I cannot detect which instance of the .open class the content came from.
You need to clone the element and append the clone:
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a.clone());
$window.fadeIn(300);
});
Demo

How to retrieve the html tag attributes in jquery and javascript?

I have tried the following code to draw a table from an array and retrieve the attribute id from the rows. Any suggestions would be appreciated immensely.
$(document).ready(function(){
$.get('php/php.php', function(data){
$.each(data, function(index, value){
$('table').append(
"<tr id='someid'>"
+"<td>"+value.ticker+"</td>"
+"<td>"+value.bid+"</td>"
+"</tr>");
});
}, "json");
$('tr').click(function(){
var id = $(this).attr("id");
alert(id);
})
});
You are binding click events to elements that do not yet exist, since they are constructed in an asynchronous callback. Instead of using click, use on. Since your table is not dynamically constructed, you can attach the on handler to that.
$('table').on('click', 'tr', function () {
...
});
http://api.jquery.com/on/
also, you're generating multiple <tr>s that all have the same ID; that is not valid markup.
Since you are dynamically injecting the new content to the DOM, It is not aware of the click event you bounded. so your click event won't work.
Solution : use jQuery on
$(document).on("click","tr",function(){
var id = $(this).attr("id");
alert(id);
})
This method is available from jQuery 1.7+ version. If you are using an older version , you may consider using delegate
As of jQuery 1.7, the .live() & .delegate() method is deprecated. use on method.
Everything is fine but you have just missed the semicolon at the end of tr click event
$('tr').click(function(){
var id = $(this).attr("id");
alert(id);
});
This will alert the id of the tr if the tr id is unique
Make Sure that in any syntax error will not allow jquery code execution.

Jquery get id or class from dynamic element

Let say I have 5 element from PHP query (so it is dynamic)
Illustrated below:
element 1 class=element id=id_1
element 2 class=element id=id_2
element 3 class=element id=id_3
element 4 class=element id=id_4
element 5 class=element id=id_5
We ussulay use jquery event by knowing their class or id, but in this case, we don't know exactly their id.
$("#id_3").click(function()
{
//in this case we have known we want to add event when we click id_3
});
How to deal with dynamic element from PHP query?
For example, how can we know that we click on element 3 with id_3?
What must we fill in $(????).click();?
When I use class, how can I know which id I reference from the class clicked?
This was the only way I could get it to work. For example, if you wanted to get the attribute ID or the value of the element that has been clicked...
$("containerElem").on("click", "someElemID", function(evt) {
var getElemID = $(evt.target).attr("id");
var getVal = $(evt.target).val();
});
In your example the elements all have the same class, so you can setup your event handler based on that:
$(".element").click(function() {
// "this" refers to the clicked element
// this.id will be the id of the clicked element
});
Or if these elements are dynamic in the sense of being loaded via Ajax at some point after the initial page load use a delegated event handler:
$("somecontainerelement").on("click", ".element", function() {
// do something with this.id
});
Where "somecontainerelement" would ideally be the element that the dynamic elements are added to, but could just be document.
If they all have the same class, then you can use a class selector. Then use this to find whatever property you are after.
$('.element').click(
$(this).prop('id');
);
If you want to add a click only then why not add that to the generated html on server side?
You can use attribute starsWith selector & on to bind events on dynamically created elements.
$('body').on('click', '[id^=id]', function(e){
});
This is veryusefull when we work on unknown elements with id or class
$( document ).ready(function() {
// user this if element is div
$('div[id^="id_"]').on('click', function() {
alert($(this).attr('id'));
});
// user this if element is input
$('input[id^="id_"]').on('click', function() {
alert(this.id);
});
});

Categories