Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from SweetAlert2 select box?

I have the following code... which is used for a sweet alert text box

swal({
  title: 'Select an Item',
  input: 'select',
  inputOptions: listOfItemsForSelectBox,
  inputPlaceholder: 'Select country',
  showCancelButton: true,
  inputValidator: function (value) {
    return new Promise(function (resolve, reject) {
      if (value != null) {
        resolve()
      }
    })
  }
}).then(function (result) {
  swal({
    type: 'success',
    html: 'You selected: ' + result
  })
})

For some reason, it just returns "true" in the 'You selected' part...

I want to get the item's id.

like image 479
IWishIWasABarista Avatar asked Jan 30 '23 02:01

IWishIWasABarista


2 Answers

Example from swal2 official docs works fine. Check your listOfItemsForSelectBox, perhaps it has some wrong format.

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
  })
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.js"></script>
like image 111
Maksim Nesterenko Avatar answered Feb 02 '23 16:02

Maksim Nesterenko


}).then(function (result) {
  swal({
    type: 'success',
    html: 'You selected: ' + result
  })
})

should be

}).then(function (result) {
  swal({
    type: 'success',
    html: 'You selected: ' + result.value
  })
})

if you output 'result' to a console you will see all the data that is associated with the 'result' variable. (i.e. console.log(result))

like image 42
Gooch Avatar answered Feb 02 '23 17:02

Gooch