I am wondering if it possible to allow both select dropdown list and a input textarea within the same sweet alert.
For example: my select list have 4 options and the last option is others. I want when user choose others and it will display a text area for the user to enter. I am using similar to what sweetalert 2 give as shown below.
swal({
title: 'Select field validation',
input: 'select',
inputOptions: {
'apples': 'Apples',
'bananas': 'Bananas',
'grapes': 'Grapes',
'Others': 'Others'
},
inputPlaceholder: 'Select a fruit',
showCancelButton: true,
inputValidator: (value) => {
return new Promise((resolve) => {
if (value === 'oranges') {
resolve()
} else {
resolve('You need to select oranges :)')
}
})
}
})
if (fruit) {
swal('You selected: ' + fruit)
}
One possible way (if you want to keep using the input
and inputValidator
) is that you can use the html
property of swal to add an hidden text input (e.g. using display: none
):
html: '<input type="text" id="fruit-text" class="swal2-input" style="display: none;">',
Then you can use the onBeforeOpen
to subscribe to change event on the input, e.g.:
onBeforeOpen: (dom) => {
swal.getInput().onchange = function (event) {
if (event.target.value === "Others") {
dom.querySelector('#fruit-text').style.display = 'initial'
} else {
dom.querySelector('#fruit-text').style.display = 'none'
}
}
},
An example of that can be found at https://south-carol.glitch.me/
Note that in this case, you should use the preConfirm
to handle the status of the swal and return the value of the text input if needed (see source of the example at the url above)