1

I am creating button like this:

    if(this.error_msg) {
        let btn_err = document.createElement('button');
        btn_err.type = "button";
        btn_err.name = "add";
        btn_err.textContent = "Remove";
        btn_err.setAttribute("class", "btn btn-primary btn-sm");

        btn_wrapper.append(btn_err);

        toastBody.append(btn_wrapper);
    }        

How can I show this.error_msg on button click as alert?

1
  • 3
    add an event listener to the button to call the alert Commented May 2, 2022 at 19:02

2 Answers 2

2

You can add an event listener to the button using javascript.

btn_err.onclick = function(){alert(this.error_msg)}
Sign up to request clarification or add additional context in comments.

1 Comment

I can´t access this.error_msg in the function. Should I declare a variable one line before?
1

You can do like this

Note: I have changed if argument as true since you did not share your whole code, it is just to show working example

const testFunction = () => {
  if(true) {
          let btn_err = document.createElement('button');
          btn_err.type = "button";
          btn_err.name = "add";
          btn_err.textContent = "Remove";
          btn_err.setAttribute("class", "btn btn-primary btn-sm");
          btn_err.onclick = function(){alert("Error message")}
          let btn_wrapper = document.getElementById("buttonWrapper")
          btn_wrapper.append(btn_err);
      }    
 }
 testFunction();
<div id="buttonWrapper">

</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.