Search code examples
javascriptjqueryjquery-uijquery-dialog

Get Data From Button Click on AutoGenerated Button - jQuery Dialog


I need to be able to get the context of the button that was clicked on a jQuery dialog.

I have a function that auto creates a dialog with a button name array I pass it. The function looks like this.

function setAutoDialog(buttonNameArray){
    var testArray = buttonNameArray;
    var passDataBack = function () {
        var test = $('.getButtonClicked').text(); // NEED THE TEXT FROM THE BUTTON THAT WAS CLICKED HERE
        $(this).dialog("close");
    }
    var myButtons = {};

    for(var i=0; i<testArray.length; i++){
        myButtons[testArray[i]] = passDataBack;
    }

    $('#autoDialog').dialog({
        autoOpen: false,
        dialogClass: 'autoDialog',
        width: 'auto',
        buttons : myButtons
    });
}

I am not sure what selector I need to use to get the value of the button that was clicked on the dialog. For example, if you have a button named "Cancel", when I click "Cancel" I need to get that text and perform operations on said text. (Pass it back to main screen)


Solution

  • Figured it out.

    On your handler, pass the click event into the function. Like so.

    $('#button1').live('click', function () {    
        setAutoDialog(buttonArray, $(this));
        $( "#autoDialog" ).dialog("open");
    });
    

    Then in your function reference the event and get the textContent from the target.

    function setAutoDialog(buttonNameArray, clickEvent){
        var testArray = buttonNameArray;
        var passDataBack = function (clickEvent) {
            var t2 = clickEvent.target.textContent;
    
            $(this).dialog("close");
        }
        var myButtons = {};
    
        for(var i=0; i<testArray.length; i++){
            myButtons[testArray[i]] = passDataBack;
        }
    
        $('#autoDialog').dialog({
            autoOpen: false,
            dialogClass: 'autoDialog',
            width: 'auto',
            buttons : myButtons
        });
    }