MAX POWER
MAX POWER

Reputation: 5448

jQuery UI dialog - add handler for custom button

I added a custom button to my jQuery UI dialog titlebar, as follows:

$('#dialog').html(html);
$('#dialog').dialog({
    modal: true,
    open: function(event, ui) {
        $(".ui-dialog-titlebar").append("<a href=\"#variants\" id=\"variants-button\"><img src=\"admin-images/variants-button.png\" alt=\"Variants\" /></a>");
    }
});

Now I need to add a 'click' handler to this button, but I am struggling with this.

$('#variants-button').click(function(){
    $('#information').hide();
    $('#variants').show();
    return false;
});

This doesn't do anything. I have also tried putting the click handler in a 'delegate' but that doesn't work either. Any ideas?

EDIT: zysoft has provided the correct solution, but I need this to work with multiple dialogs on the page. It does not seem to work as expected with multiple dialogs.

Upvotes: 3

Views: 2555

Answers (3)

David Hoerster
David Hoerster

Reputation: 28701

Why don't you just create the click handler after you append the new button?

$('#dialog').html(html);
$('#dialog').dialog({
    modal: true,
    open: function(event, ui) {
        $(".ui-dialog-titlebar").append("<a href=\"#variants\" id=\"variants-button\"><img src=\"admin-images/variants-button.png\" alt=\"Variants\" /></a>");
        $('#variants-button').click(function(){
            $('#information').hide();
            $('#variants').show();
            return false;
        });
    }
});

If you add the event handler after you add the element to the DOM, you should be OK.

UPDATE Based on your update, if you wanted to do something like this to multiple dialog title buttons, a delegate may be better (since you'll avoid having to do this for every dialog).

You could apply a class to your button (e.g. variant-class) that acts as a marker class that you'll use as a selector to your on handler:

$('.variant-class').on('click', function() {
  $('#information').hide();
  $('#variants').show();
  return false;
});

I hope this helps. Good luck!

Upvotes: 2

zysoft
zysoft

Reputation: 2358

Your button is added in runtime when dialog opens. It seems to happen after you assign click handler. Try this:

$('#variants-button').live('click', function(){
    $('#information').hide();
    $('#variants').show();
    return false;
});

Upvotes: 2

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

Do you execute after you append the the HTML? If not, try using jQuery live insteed.

$('#variants-button').click(function(){
    $('#information').hide();
    $('#variants').show();
    return false;
});

Upvotes: 0

Related Questions