problem dynamically adding buttons to dialog

problem dynamically adding buttons to dialog

I have the code you can see below. The problem is, that whenever I click one of the submit buttons, it always sends the data of the leftmost (added last) button, rather than the button it belongs to. Any ideas how I can fix this?

    dialog.find("form").submit(function(event) {
        event.preventDefault();
    })
    .find("input:[type='submit']").each(function() {
        var form = $(this).parents('form').eq(0);
        var el = $(this);
        buttondata = el.attr('name') + "=" + el.attr('value');
        buttons[el.attr('value')] = function() {
            data = form.serialize();
            data += (data.length > 0 ? "&" : "") + buttondata;
            alert(data);
            dialog.loadPage(
                $.urlParser.setBaseUrl(dialogUrl).parse(form.attr('action')).assemble(),
                form.attr('method'),
                data
            );
        };
        $(this).remove();
    });
    dialog.dialog('option', 'buttons', buttons);