display the text conditionally in a sweetalert modal

The error was lead by a typo in this line

cancelButtonText; 'No'

where I typed a ; instead of :

Voted to close it as Typo

I am using sweetalert2 on a page where I want to show a modal. The modal should have a text dependent from a condition. So I tried to do:

var action='enable';
Swal.fire({
        title: 'Confermi?',
        text: if(action=='enable'){'Riattivare l\'anagrafica selezionata?'}else{'Disabilitare l\'anagrafica selezionata?'},
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText; 'No'
    }).then((result) => {

but this will lead to the following error:

Uncaught syntax error: missing : after property id

This error is caused by this line:

text: if(action=='enable'){'Riattivare l\'anagrafica selezionata?'}else{'Disabilitare l\'anagrafica selezionata?'},

I also tried to use:

text: action=='enable'?'Riattivare l\'anagrafica selezionata?':'Disabilitare l\'anagrafica selezionata?',

but they are equivalent and lead to the same error.

What is the correct syntax to use to make a property value dinamyc based on the value of a variable?

2 thoughts on “display the text conditionally in a sweetalert modal”

  1. use a ternary operator for option text (parenthesis is important):

    text: (action=='enable'? 'Riattivare l\'anagrafica selezionata?': 'Disabilitare l\'anagrafica selezionata?'),
    
    Reply
  2. Use a ternary operator:

    var action='enable';
    Swal.fire({
      title: 'Confermi?',
      text: action=='enable' ? 'Riattivare l\'anagrafica selezionata?' : 'Disabilitare l\'anagrafica selezionata?',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Si!',
      cancelButtonText; 'No'
    }).then((result) => { /* ... */ })
    
    Reply

Leave a Comment