3

I create a custom button inside a footer in Sweetalert2 like this.

    Swal.fire({
          icon: "question",
          showCancelButton: true,
          confirmButtonColor: "#1976d2",
          cancelButtonText: "No",
          confirmButtonText: "Sí",
          footer: "<button (click)='withoutread()' class='btn btn-info'>Test</button>"
  })

  withoutread() {
    console.log('hello');
  }

The problem: The function withoutread doesn´t call properly, console.log('hello') doesn´t show hello in console.

So: What´s wrong in this code?

Wasim
  • 600
  • 2
  • 11
  • 32
El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92

4 Answers4

1

Working !

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<button id="buttonId">Test</button>'
})

document.getElementById('buttonId').onclick = function(){
    alert('do Something');
}
Tushar Wasson
  • 494
  • 5
  • 10
  • Inside that onclick handler, how can we access any typescript variable? – Naseem Ahamed Apr 12 '22 at 11:18
  • Just pass the variable in function document.getElementById('buttonId').onclick = function(var1 , var2){//body} – Tushar Wasson Apr 13 '22 at 12:04
  • Those are variables within the event scope. Can a JS event handler access the typescript local and instance variables? For example, `sampleFunction(traceId){` Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong!', footer: '' }) `document.getElementById('buttonId').onclick = function(){ //May I know how I can access the traceId local variable here? }` } – Naseem Ahamed Apr 14 '22 at 09:35
0

Your click method in the way you have implemented it would not be accessible since the method withoutread() exists outside of the scope of the SweetAlert instance.

Aside from the SweetAlert configurations available for capturing user input, you could include a third, custom button and capture the click using event delegation as described here

DevMike
  • 1,630
  • 2
  • 19
  • 33
0

Try this

footer: "<a><button (click)='withoutread()' class='btn btn-info'>Test</button></a>"

OR

footer: "<a onclick='withoutread()'><button class='btn btn-info'>Test</button></a>"
Wasim
  • 600
  • 2
  • 11
  • 32
0

You have to user onclick rather than (click). Please look at the below working code.

Swal.fire({
      icon: "question",
      showCancelButton: true,
      confirmButtonColor: "#1976d2",
      cancelButtonText: "No",
      confirmButtonText: "Sí",
      footer: "<button onclick='withoutread()' class='btn btn-info'>Test</button>"
})
 function withoutread() {
     alert('dd') 
 }

You can also review the JSFiddle link here

saumil_
  • 304
  • 2
  • 11