SweetAlert2 add dynamic options to select input

12,657

You Could possibly try building up the options object like this.

function linkThing() {

        //this i assume would be loaded via ajax or something?
        var myArrayOfThings = [
            { id: 1, name: 'Item 1' },
            { id: 2, name: 'Item 2' },
            { id: 3, name: 'Item 3' }
        ];

        var options = {};
        $.map(myArrayOfThings,
            function(o) {
                options[o.id] = o.name;
            });

        swal({
            title: 'My Title',
            text: 'Please select an option',
            input: 'select',
            inputOptions: options,
            showCancelButton: true,
            animation: 'slide-from-top',
            inputPlaceholder: 'Please select'
        }).then(function (inputValue) {
            if (inputValue) {

                console.log(inputValue);

            }
        });
    };
Share:
12,657
Andrei Zamfir
Author by

Andrei Zamfir

Updated on June 12, 2022

Comments

  • Andrei Zamfir
    Andrei Zamfir about 2 years

    I want to add dynamic options to a SweetAlert2 input type select that looks like this:

    swal({
    title: 'Select Ukraine',
    input: 'select',
    inputOptions: {
      'SRB': 'Serbia',
      'UKR': 'Ukraine',
      'HRV': 'Croatia'
    },
    inputPlaceholder: 'Select country',
    showCancelButton: true,
    inputValidator: function(value) {
      return new Promise(function(resolve, reject) {
        if (value === 'UKR') {
          resolve();
        } else {
          reject('You need to select Ukraine :)');
        }
      });
    }
    }).then(function(result) {
      swal({
        type: 'success',
        html: 'You selected: ' + result
      });
    })
    

    Instead of those 3 countries I want to add my own options which are saved in an object. How can I do that using javascript?