从SweetAlert2选择框中获取价值?

时间:2017-06-30 20:52:14

标签: javascript sweetalert sweetalert2

我有以下代码...用于甜蜜警报文本框

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
  })
})

出于某种原因,它只会返回" true"在你选择的'部分...

我想获得该项目的ID。

2 个答案:

答案 0 :(得分:2)

来自swal2 official docs的示例正常工作。检查您的listOfItemsForSelectBox,可能是格式错误。

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>

答案 1 :(得分:0)

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

应该

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

如果您将“result”输出到控制台,您将看到与“result”变量关联的所有数据。 (即 console.log(result))