How do you add a error message when a user presses a button?

How do you add an error message when a user presses a button on a panel? For example is, if you have no open files an alert should show the error. If a document is open then no alert is shown.

here is a quick example

document.getElementById("saveButton").addEventListener("click", async function () {
   if(document.getElementById("filename").value == ""){
      alert("Please enter an export filename.");
      return;
   }

)};

Thank you, let me see if I can adapt it to:

[...document.body.querySelectorAll('[data-snippet="button_1"]')].forEach(button => button.addEventListener("click",button_1));

I am trying to make an alert popup when someone clicks a button when there is no open document.

const app = require("photoshop").app;

// Function to show an alert if there is no active document
function showAlertIfNoActiveDocument() {
  if (!app.activeDocument) {
    alert("There is no active document.");
  }
}

// Add an event listener to the "Go" button click event
const goButton = document.getElementById("go-button");
goButton.addEventListener("click", showAlertIfNoActiveDocument);

Thank you, I will give this a shot.

I made a small tweak to the @JasonM 's solution. In this case, you would use the UXP interface to show the alert

const app = require("photoshop").app;

// Function to show an alert if there is no active document
function showAlertIfNoActiveDocument() {
  if (!app.activeDocument) {
  //Use the Photoshop Interface to show an alert pop up
    app.showAlert("There is no active document.");
  }
}

// Add an event listener to the "Go" button click event
<sp-button onClick={showAlertIfNoActiveDocument()}> Show Alert <sp-button>

This works great but what if I have multiple buttons that I want to have the same alert? Is there another way instead of this?

// Function to show an alert if there is no active document
function showAlertIfNoActiveDocument() {
  if (!app.activeDocument) {
    alert("There is no active document.");
  }
}

// Add an event listener to the "Go" button click event
const goButton = document.getElementById("go-button");
goButton.addEventListener("click", showAlertIfNoActiveDocument);

const goButton2 = document.getElementById("go-button");
goButton2.addEventListener("click", showAlertIfNoActiveDocument);

Give all your buttons the same class and then you can add an event listener to all of these buttons like this:

document.querySelectorAll('.my-button-class').forEach(button => {
    button.addEventListener('click', showAlertIfNoActiveDocument);
});

This is JavaScript and no special UXP stuff. Maybe you should take a JavaScript course :slight_smile:

I really do need a javascript class, I’m not joking as you can see. Thank you for all your help. I appreciate it.