Maxlight Maxlight - 2 months ago 42
jQuery Question

SweetAlert2 detect radio button select

I am using SweetAlert2 javascript library to show popups. SweetAlert2 is a fork of SweetAlert which was not maintained anymore. SweetAlert2 allows me to add radio buttons like this

// inputOptions can be an object or Promise
var inputOptions = new Promise(function(resolve) {
resolve({
'#ff0000': 'Red',
'#00ff00': 'Green',
'#0000ff': 'Blue'
});
});

swal({
title: 'Select color',
input: 'radio',
inputOptions: inputOptions,
inputValidator: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
resolve();
} else {
reject('You need to select something!');
}
});
}
}).then(function(result) {
swal({
type: 'success',
html: 'You selected: ' + result
});
})


SweetAlert2 give 'swal2-radio' name to the radio inputs, like this

<input id="swal2-radio-1" type="radio" name="swal2-radio" value="3">


So I try to listen for swal2-radio for any clicks like this:

$("input[name='swal2-radio']").on("click", function() {
var id = $('input[name=swal2-radio]:checked').val();
console.log('id: ' + id);
});


It should print to console so that I know it worked.

Here is the code that I have so far:
https://jsfiddle.net/ayx0fkz3/

Am I doing something wrong or is this not working because of how SweetAlert2 works?

Answer

you have to bind event by delegation event binding with whole document.

$(document).on("click",".swal2-container input[name='swal2-radio']", function() {
    var id = $('input[name=swal2-radio]:checked').val();
    console.log('id: ' + id);
});

Check Fiddle Link

Comments