0

I have some posts which are coming from database. These posts are added to page after the page get loaded by ajax. I am adding a delete button on every post and every button has an id. Here is my code :

<i class="fa fa-trash" id="unique-id"></i>

Now I want to access these buttons in jQuery through their id on onclick() method but the problem is that these buttons are added in page after the page is loaded and I guess jQuery methods can only be called inside a document ready function. So currently I doing this in following way :

<i class="fa fa-trash" onclick="delPost('id')"></i>

and here is some javascript :

function delPost(id) {

    var post_id = id;
    var post = "#post_"+id;

    $(post).fadeOut(300, function() {
        $.ajax({

            type : 'POST',
            url  : 'update.php',
            data: ({id : post_id, act : "rem-post"}),
            success : function()
            {
                // Some Function
            }
        }); //End of Ajax
    });

}

I want this function to be called with jQuery... Is this possible ??

Shehzad
  • 337
  • 4
  • 25
  • Possible duplicate of [jQuery click handler function does not fire on element added after DOM load](http://stackoverflow.com/questions/21193378/jquery-click-handler-function-does-not-fire-on-element-added-after-dom-load) – Summer Developer Feb 28 '17 at 18:32
  • Can you try this simple addition `$(document).find(post).fadeOut(...` ? – Louys Patrice Bessette Feb 28 '17 at 18:40

4 Answers4

1

I would do something like this:

Html:

<div class="post">
    ...
    <i class="fa fa-trash deleteButton" data-id="unique-post-id-here"></i>
</div>

Js:

$(body).on("click", ".deleteButton", function() {
    var post_id = $(this).attr("data-id");
    delPost(post_id);
});

I chose the "body" element to the "on" event because for it to work with dynamically added elements, it must be called on static elements, which are there from the begining. You could also use some ".posts-container" element or similar, you only have to make sure it is there when the page loads.

norim_13
  • 303
  • 2
  • 11
  • when i will select with class say .delete it will select all elements with .delete class and store them in array so i must have to specify index of : var id= $(this).attr('id'); to get id – Shehzad Feb 28 '17 at 19:16
  • You shouldn't select with the button's class, but with the "this" selector, as I wrote in the code. It should select only the clicked button. – norim_13 Feb 28 '17 at 23:04
1

EDIT

So what you want to use id like this:

<i class="fa fa-trash" id="unique-id"></i>

Then, try this function:

$(document).on('click','.fa-trash',function(){

    var post_id = $(this).attr('id');

    $(this).closest(".post").fadeOut(300, function() {
        $.ajax({

            type : 'POST',
            url  : 'update.php',
            data: ({id : post_id, act : "rem-post"}),
            success : function()
            {
                // Some Function
            }
        }); //End of Ajax
    });
});

It will pass the correct id to Ajax and fade out its .post parent.

The problem with your function is not to retreive the correct id...
But to make a jQuery lookup using it.

On this line:

$(post).fadeOut(300, function() {

Even with the right id, the element you want to target is not in dom.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • my current code is working very fine but i just want to remove onclick function foro and instead i want to call this method from jquery onclick method in script. – Shehzad Feb 28 '17 at 18:59
  • when i will select with class say .delete it will select all elements with .delete class and store them in array so i must have to specify index of : var id= $(this).attr('id'); to get id – Shehzad Feb 28 '17 at 19:28
  • I don't get your array idea. I tought you wanted an onclick fadeout and ajax update. – Louys Patrice Bessette Feb 28 '17 at 19:31
  • 1
    oh i got it man .... just excuse me as i was confused a little bit ... thanks alot your solution is working perfectly :-) – Shehzad Feb 28 '17 at 19:39
0

You can make use of event delegation concept here.

Try to add events to only those images within the document with class fa-trash .With delegation it takes care of all images which are part of the dom even which are added dynamically too

check the following snippet

$(document).ready(function(){
  $(document).on('click','i.fa-trash',function(){
      var id= $(this).attr('id')
      //alert(id)
     // delPost(id);
  });
});


function delPost(id) {

    var post_id = id;
    var post = "#post_"+id;

    $(post).fadeOut(300, function() {
        $.ajax({

            type : 'POST',
            url  : 'update.php',
            data: ({id : post_id, act : "rem-post"}),
            success : function()
            {
                // Some Function
            }
        }); //End of Ajax
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i class="fa fa-trash" onclick="delPost('id')" id="unique-id">this is del</i>
<i>hello</i>
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • when i will select with class say .delete it will select all elements with .delete class and store them in array so i must have to specify index of : var id= $(this).attr('id'); to get id – Shehzad Feb 28 '17 at 19:12
  • yes that's what you have to do.. In the code im trying to access the id and passing the same to a function – Geeky Feb 28 '17 at 19:14
  • but how can i know that from an array of elements which element is clicked ?? – Shehzad Feb 28 '17 at 19:18
  • not exactly clear what you are asking but when there are array of images ad when you click on an image ,you would be able to acess that perticular iamge details – Geeky Feb 28 '17 at 19:28
  • oh i got it man .... just excuse me as i was confused a little bit ... thanks alot your solution is working perfectly :-) – Shehzad Feb 28 '17 at 19:38
  • If it is of any help consider upvoting/accepting the answer :p – Geeky Feb 28 '17 at 20:42
  • yeah it's a good manner to say thanks to person who helps you but i can't record my vote as i am new user :') and i guess only one answer can be accepted at a time on stack overflow ... :) – Shehzad Mar 01 '17 at 10:22
-1

remove the onclick from the element, and add an id and/or class (for instance class="deleteThis" data-id="4483339"). then create an event handler in the document.ready with something like this:

$( ".deleteThis" ).on( "click", delPost( $(this).attr('data-id' );

example code to be found at http://api.jquery.com/on/

Non Plus Ultra
  • 867
  • 7
  • 17