Search code examples
jqueryuser-interfacejquery-uiclickjquery-ui-dialog

How can I get value of the button id from jquery ui dialog when user click?


I want to create a jQuery UI dialog dynamically. Number of buttons in dialog depend on my JSON data. I need the button id when user click on it.

var deviceInfo = {
    "devices": [{ "deviceID": "11", "devicename": "test12" },
                { "deviceID": "12", "devicename": "test12" }]
};

for (var x in deviceInfo["devices"]) {
    arrButtons.push({
        text: "DeviceID:" + deviceInfo["devices"][x]["deviceID"], 
              id: deviceInfo["devices"][x]["deviceID"], click: function () {
            currentDeviceID = deviceInfo["devices"][x]["deviceID"];
            console.log("selected id:", currentDeviceID);
            $(this).dialog("close");
        }
    });
}

showDeviceID = function (dID) {
    console.log("deviceID", dID);
}

$("#dialog").dialog({
    modal: true,
    dialogClass: 'no-close',
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    },
    buttons: arrButtons
});

Every time I get last id. Would you please help me?


Solution

  • Just use event properties of the click handler.

    $('button').click(function(e)
    {
       e.target.id; // gives you the id of the button clicked.
    }