ondrums ondrums - 2 years ago 81
HTML Question

Own buttons in jquery dialog not working

I am creating an application with a lot of textareas and one button for each textarea.
If the user edits content, it will be saved into the database.
When clicking on the button, a dialog opens and displays all earlier versions of the content of that specific area.
This is loaded by .html() in that dialog.
Now I want a button on each earlier version in that dialog. When clicking on that button, this earlier version should copied to the textarea of the "main" site.

My problem: I could not get the buttons working, not even with an alert.
Where am I wrong?

Open the dialog, working:

$( ".historydialog" ).click(function( event ) {
var idhist = $(this).attr('id');
$( "#dialog" ).dialog({
open: function(event, ui) {
$.get( "getLangHist.php", { idhist: idhist }, function( data ) {
$( "#divInDialog" ).html( data );
maxHeight: 500,
width: 600,
height: 500

The button in the dialog:

<button id="history-{id}" class="historybutton">

Button action, not working:

$(".historybutton").click(function( event ) {

Answer Source

You mention that you're adding the content to the dialog using .html()

This would imply that you're dynamically adding the content to the DOM

If this is the case, then you can change your click handler to this:

$(document).on('click', '.historybutton', function(){

This will bind the click handler to dynamically added content.

As a side-note. Rather than pepper your controls with delimited ID's, like "history-{id}" you could use data- attributes. It's far more obvious when looking through the code too.

So your button would be:

<button data-history-id="123" class="historybutton">history</button>

You can then access this using the data method in jQuery

var hId = $('.historybutton').data('history-id');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download