0

I have empty div that appends another div with jQuery function:

<div id="files_wrapper"> //comes on start
   <div id="delete">delete</div> //will be dynamically created
</div>

I want event on a click:

$(document).ready(function() {
$("#delete").click(function(){
console.log("delete");
});
}

But nothing happens on a click. How to make it work?

Ruslan Lomov
  • 485
  • 1
  • 7
  • 20

3 Answers3

0

Its an ID so you follow it with a # sign.

So like this:

$(document).ready(function(){
  
  $("#delete").click(function(){
    alert("Deleted")
     $(this).fadeOut(500);
    })
  })
<!DOCTYPE html>
<html lang="en-US">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  </head>
<div id="files_wrapper"> 
   <button id="delete">Delete</button> 
</div>
  </html>
amanuel2
  • 4,508
  • 4
  • 36
  • 67
0

I found the answer:

$(document).on('click', '#delete', function() {
                                console.log("delete");
                            });
Ruslan Lomov
  • 485
  • 1
  • 7
  • 20
0

HTML: As I understand it, you're starting with something like this...

<div id="files_wrapper">Stuff in here</div>

And, you might then add some button that creates a new button within your application:

<div class="action add" data-type="file-delete">Add Option (Delete)</div>

JavaScript: You need to add some script to add a button, which itself as a listener.

// Find your application section
var app = $('#files_wrapper');

// Make an element to clone
var deleteFile = $('<div>').addClass('action delete').html('Delete file');

// Find your trigger that adds the button
$('.action.add[data-type="file-delete"]').on('click.fileaction', function () {
    // Clone your template button
    var deleteButton = deleteFile.clone();

    // Add your listener that reponds to the delete button being pressed
    deleteButton.on('click.delete-file', function () {
        $(this).toggleClass('clicked')
    })

    // Add it to the application
    app.append(deleteButton)

})

This is the kind of thing that you want to do to build a DRY application using jQuery.

jsFiddle example: https://jsfiddle.net/likestothink/shra07Lp/1/

Darren L
  • 94
  • 3