Dynamically removing elements from different div - javascript

I have the following code:
<div id='a'>
</div>
....
....
<div id='b'>
</div>
combined the script:
$.ajax({
type:'POST',
url:'grouplist.php',
async:false,
dataType:'json',
cache:false,
success:function(result)
{
var $ni=$('#a');
$.each(result,function(key,value)
{
var $button=$('<input></input>',{
'type':'button',
'id':key,
'class':'button',
'value':value
}).appendTo($ni);
});
}});
This creates buttons in the div with a dynamic id. Now I am dynamically adding elements into div with id b if I click on one of these buttons as follows:
$('#a').on('click','.button',function(){
$('.hmm').remove();
var x=$(this).attr('id');
$.ajax({
type:'POST',
url:'groupmsg.php',
async:false,
data:'id='+x,
dataType:'json',
cache:false,
success:function(result)
{
var $na=$('#groups');
$.each(result,function(key,value)
{
var t_msg=value[0]+":"+value[1]+"\t"+value[2];
var $p = $('<p></p>'{'id':'msg'+key,'class':'.hmm'}).html(t_msg).prependTo($na);
});
}
});});
I am unable to remove the elements of div#b using $('.hmm').remove();. Can someone help me in this regard?

There is an error in your code, should be:
var $p = $('<p></p>',{'id':'msg'+key,'class':'hmm'})
No dot (.) should be used when setting class.

Seems like you are attaching click event to the div with id=a and clicking on button which is created inside another element. Try to attach click event to document instead.
$(document).on('click','.button',function(){
// ...
});

Related

Turning jquery into an includable, callable function

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!
I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.
To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview

jQuery select every time first element

HTML:
<div class="vote" id="<?php echo $id; ?>">
jQuery:
$('.vote').on('click', function() {
var div = $(".vote").attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(".vote").attr('id')
},
success: function(data) {
alert(div);
}
});
});
this works, but div var it's always first element - and runs twice (two divs with vote class).
I use AJAX for displaying results (divs with vote class) also.
Why is this happening and how can I fix?
You need to use this, which refers to element which invoked the element.
var div = $(this).attr('id'); //this.id;
When you are using $(".vote").attr('id') it will always return you id of first element.
As you are using id to store custom data. I would recommend you to use data-* prefixed custom attribute which can be fetched by using .data()
<div class="vote" data-id="<?php echo $id; ?>">
Then you can use
var id = $(this).data('id');
You need to use current elements clicked context this:
var div = this.id;
Replace your $('.vote') to $(this) like this below:
$('.vote').on('click', function() {
var div = $(this).attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(this).attr('id')
},
success: function(data) {
alert(div);
}
});
});
Use this.id instead of $('.vote').attr('id'), because javascript will get the first id he founds if you use $('.vote').attr('id')

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

How to replace .live() method with .on() method

Hei.. I have a function to load more news. Since jquery-1.9.1.min.js this function was working alright, but now I have to replace it with .on() method and I still can't get it work.
Here is the code:
// Load more news feed
$(function(){
var page = 1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true",
dataType:'json',
success: function(data){
$("#the_news_feed").html(data.news_feed);
if(page <= data.total_pages){
$("#the_news_feed").after('<button id="load_more_feed" class="btn btn-primary btn-large" style="width: 100%;margin-top:10px">Load More</button>');
}
}
});
$("#load_more_feed").live("click", function(){
var next = page+=1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true&page_num="+next,
dataType: "json",
success: function(data){
$("#the_news_feed").append(data.news_feed);
if(next == data.total_pages){
$("#load_more_feed").remove();
} else {
$("#load_more_feed").html("Load More");
}
},
beforeSend: function(){
$("#load_more_feed").html("Loading...");
}
});
});
});
I tryed to replace:
$("#load_more_feed").live("click", function()
with
$("#the_news_feed").on("click", "load_more_feed", function()
but I still can't get it work. What am I doing wrong? Thank you!
I display this function with id="news_feed" so here was the problem
<div class="tab-pane fade" id="news_feed">
<div id="the_news_feed"></div>
</div>
Final solution is $("#news_feed").on("click", "load_more_feed", function()
Thank you guys!
Actually, you're missing the # in the id selector.
$("#the_news_feed").on("click", "load_more_feed", function()
must be
$("#the_news_feed").on("click", "#load_more_feed", function()
assuming #the_news_feed is the parent of #load_more_feed.
EDIT :
From your code, you're appending this #loadmore button after #the_news_feed, so this obviously will not work. Try changing it to this :
$(document).on("click", "#load_more_feed", function()
This will bind the click to the document, which will always exist. Alternatively, you could bind it to #load_more_feed closest static parent, like an element which exists when you load your page and not dynamically created.

jQuery selectors after dynamic reload, and $(this)

I need some help. I load a list of entries in a div every 5 seconds. Each entry is a div and has a unique ID. Like this:
<div class="entry">
<div class="textbox">
<p class="entry-text">
<?php echo $text;?>
</p>
</div>
<div class="infobox">
<p class="date"><a #<?php echo $id;?> id="<?php echo $id;?>" href="gen_details.php?id=<?php echo $id;?>"><?php echo $t;?></a> </p>
<p class="ip"><?php echo $ip;?></p>
</div>
These, as I said are loaded each 5 seconds. I'm adding a details page for every entry, with this:
$('.date a').click(function () {
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
return false;
});
This works perfectly fine, until it reloads. It seems to lose the handle for the a href and instead of doing the procedure it goes to gen_details.php
I have tried to use .on() but I don't know how would I get the ID of the entry using .on(), as I cant use $(this) (afaik).
I hope I explained my problem at least half-well. English is not my first language so it wasn't that easy.
Thanks in advance.
Try this selector
$('div').on('click', '.date a', function () {
This will delegate the event to its parent div. So it should work for dynamically created elements as well.
Live click event bind event handler to element even after you reload some element. Default click event bind to element when a page load once you reload that element then it also delete event handler of that element.
works on till jquery 1.7 version.
$('.date a').live('click',(function (e) {
e.preventDefault()
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
});
//when jQuery > 1.7 then used this method
$('body').on('click' '.date a',function () {
//call
});

Categories

Resources