adding element using loop in jquery doesn't appear in dom - javascript

I am adding elements using a json call. The issue I have is that if I append an item outside the loop it appears in the DOM and I can select it, if I appended in the loop I cannot select it?
Any help would be appreciated.
<ul data-role='listview' class='ui-listview' id="DivLogOut" >
</ul>
<script type="text/javascript">
$(document).ready(function () {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
$.get("api/StaffLoggedIn.ashx?loid=" + loid, function (data) {
var jsonobj = $.parseJSON(data);
$(jsonobj).each(function (i, item) {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
})
})
$(".PersonLogout").click(function () {
alert("test");
})
})
</script>

Dynamically appended element use with on()
$(document).on("click",".PersonLogout",function () {
alert("test");
})

when added dynamically, you need to re-add the listener to your DOM element, this way Jquery knows which one to call. i suggest you add your .click method in a function that you can call after the async loop is done (your $.get) EX:
<ul data-role='listview' class='ui-listview' id="DivLogOut">
</ul>
<script type="text/javascript">
$(document).ready(function() {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
$.get("api/StaffLoggedIn.ashx?loid=" + loid, function(data) {
var jsonobj = $.parseJSON(data);
$(jsonobj).each(function(i, item) {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
})
addListener();
})
function addListener() {
$(".PersonLogout").click(function() {
alert("test");
})
}
addListener();
})
</script>

Please use .on instead of .click method. .on method will work for dynamically added elements.
$(document).on("click",".PersonLogout",function () {
//You can access the item using $(this)
});

You're creating an element after the document has loaded. AFAIK elements that are dynamically created after the document has loaded has no event binded on it.
What you can do is to bind the event on document. Remove the click event in the document ready function.
$(document).on('click', '.PersonLogout', function()
{
alert('I have been clicked!');
});

You need to listen the event outside the reloaded view, apparently $("#DivLogOut").
$("#DivLogOut").on('click', '.PersonLogout', function(){
....
});
For sure, it works ;)

Related

Is there a way to apply jQuery to dynamically created elements? (not event listeners)

I have dynamically created an element with the following class:
<span class="text">Hello</span>
and jQuery:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + " There");
}
$(function() {
$(".text").each(function(){
changeText.apply(this);
})
})
Obviously, this is a simplified version of what is actually happening but the basics are there. Is it possible to apply this rule to dynamically created elements even though we are not using event listeners?
The problem here is that there is no specific location for these ".text" elements. The only place we know these will show up is in the body. I we use a mutationObserver on the body... wouldn't that be taxing performance?
Do this instead:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + ' There');
}
$(function(){
$('.text').each(function(i, e){
changeText.call(e);
});
});
Like this
$dynamicElement.find(".text").each(function(){
changeText.apply(this);
})

Onclick event not triggered on span elements appended after AJAX call

I am retrieving some data using Ajax and appending it as span element. Below is the simplified version of the code.
function fetchPost() {
$.getJSON(urlContent, function(data) {
$.each(data.query.pages, function(i, item) {
$("#feed").append("<span id='random'> randomtitle </span>");
}
});
});
return 1;
}
$(document).ready(function(){
$('span').click(function() {
var text = $(this).text();
alert(text);
});
});
The onclick event is not triggering for span elements which was appended with the help of the AJAX call. The span elements which were present in the html before is responding to onclick event. What should I do?
The problem is you are trying to listen to elements that don't yet exist.
The solution is to use event delegation, and listen to the parent element:
$("#feed").on('click', 'span', function() { /* ... */
http://api.jquery.com/on/

Jquery on php in div box not working

I have an main php that load a php into a div box via a dropdown list.
The loaded php contains a table. There is jquery in it that does an alert on row clicked.
$(document).ready(function() {
$('#newsTable tr').click(function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});
But after it is loaded into the div, the script is not firing
use Event delegation to attach event. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).ready(function() {
$(document).on('click','#newsTable tr',function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
}); // End
There is something with event delegation. Try using this code :
$('id_Or_Class_container_hold_the_php_data').on('click', 'tr', function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
replace
(document).ready(function() {
with
$(document).ready(function() {
try this
jQuery(document).ready(function($) {
$('#newsTable tr').click(function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});
I think you need to use live query, instead of your click event u can use following.
$('#newsTable tr').on('click',function()
Use below code..i think its working properly.
$(document).ready(function() {
$("#newsTable").on('click','tr',function(){
var clickedId = $(this).children('td:first').text();
alert(clickedId);
});
});

Dynamic parameters in JQuery

I have function in which append method is taking a static parameter.
function toggle() {
$("#MS").append($('#hide'));
}
What i want is to pass the parameter dynamically from my Hyperlinks click event.
In above code that #MS is static which i want to pass dynamically
Code:
HTML
<div id="MS">
JP MORGAN<br>
</div>
I want to pass the argument from onclick to toggle method and that parameter will be used in the append method.
I have tried several combinations buut it didnt worked.
Please help..
My new code after changes
<script>
$(function() { // when the DOM is ready
var $hide = $('#hide').click(function(){
$(this).closest('div').hide();
});
$('a.toggle').click(function(e){
e.preventDefault();
$(this).parent().append($hide);
});
});
</script>
<div id="JP">
JP MORGAN<br>
</div>
still not working
Since you are using jQuery, you can add classes to your a elements and use parent method:
$(function() { // when the DOM is ready
var $hide = $('#hide').click(function(){
$(this).closest('div').hide();
});
$('a.toggle').click(function(e){
e.preventDefault();
$(this).parent().append($hide);
});
});
Retrieve the ID dynamically on the anchor's click event and pass that ID to the function:
$("a").on("click", function(e){
e.preventDefault();
$(this).append($('#hide'));
};

Jquery append input element and send data from that input element

I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});​
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});​
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
​
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/

Categories

Resources