0

i appending buttons with some IDs and i use those IDs to make on click stuff when it appending didn't take button() effect and on click it don't take the function that I created it for this button id

$("button#edit-doc").each(function() {
   $(this).button();
   $(this).on("click", function(){
       alert("clicked");
   });
});

append button

$("#append").on("click", function(){
     $('div#container').append("<button id='edit-doc'> Edit </button>");
});

container

<div id="container"></div>
Ahmed Fathi
  • 159
  • 1
  • 2
  • 11
  • `$("button#edit-doc").each` - do you have multiple elements with the same id? You shouldn't, use classes instead. – bfavaretto Jul 10 '13 at 19:02

3 Answers3

0

This seems to be what you're after:

function handler() { alert('clicked'); }

$("#append").on("click", appendButton);

function appendButton(){
    $('#container').append(function() {
      return $("<button id='edit-doc'> Edit </button>").on("click", handler);
    })
}

http://jsfiddle.net/PF8xY/

See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.

Community
  • 1
  • 1
Sparko
  • 735
  • 6
  • 15
0
$(document).on("click", "#selector", function(){
    //Your code here.
}); 

Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.

I do this in a dynamically created table that is sort-able and works great.

EDIT:

Here is an example. Click the button to add a div then click the div to get it's contents.

http://jsfiddle.net/FEzcC/1/

Iron3eagle
  • 1,077
  • 7
  • 23
0

The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.

Something like:

// Load all buttons with class=edit-doc and add event listner
$(function() {
    $("button.edit-doc").button().on("click", function(){
        alert("clicked");
    });
});

// Append button if button with id=append is clicked
$("#append").on("click", function(){
    var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
    $('div#container').append(button);
    $(button).button().on("click", function(){
        alert("clicked");
    });
});

Working example:

http://jsfiddle.net/RC9Vg/

sam
  • 330
  • 2
  • 7