Skip to content Skip to sidebar Skip to footer

Dynamic Buttons With Attributes Through Jquery

Alright, I can generate a button with code of the form var temp = ''; $('#myDiv').append(temp).click(

Solution 1:

Here's how to do it the jQuery way:

var $button = $('<button/>', {
  type: 'button',
  'class': 'dynBtn',
  id: 'anID',
  text: 'Here!',
  click: function() {
    window.alert('Hello! My id is '+ this.id);
  }
});

$button.appendTo('#myDiv');

Solution 2:

That's because .append() doesn't return the appended element, you can use .appendTo() in this case:

$(temp).appendTo('#myDiv').on('click', function() {
    window.alert("Hello! My id is " + this.id);
});

If you are adding many elements to the DOM, it would be better to use event delegation instead.

$('#myDiv').on('click', '.appendedElement', fn); 

Solution 3:

Use on(), do like this:

$(document).ready(function(){
  //in here you put the event for all elements with dynBtn class
  $(document).on("click",".dynBtn",function(){dynButtonClicked();});
});

functiondynButtonClicked (aButton) {
    window.alert("Hey, my id is " + aButton.id);    
};

//and append the button anytime you wantvar temp = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>";
$('#myDiv').append(temp);

Post a Comment for "Dynamic Buttons With Attributes Through Jquery"