How to access values in a Radio Alert

I can’t get to use/access the selected Radio button/value in an Alert in the following code:

   let alert = this.alertCtrl.create({
        title: 'Specify the reason',
        inputs: [
          {
            type: 'radio',
            label: 'label 1',
            value: '0'
          },
          {
            type: 'radio',
            label: 'label 2',
            value: '1'
          }
        ],
        buttons: [
          {
            text: 'Cancel',
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          },
          {
            text: 'OK',
            handler: () => {
              console.log('OK clicked: ' );
              // I NEED TO GET THE VALUE OF THE SELECTED RADIO BUTTON HERE
            }
          }
        ]
      });
      alert.present();

Try to change your handler like this:

handler: data => {
            console.log('OK clicked. Data -> ' + JSON.stringify(data));
            }

Gives me a TS error: cannot find name “data”.

Did you add data in handler callback?

1 Like

oopss, good point! Added it, but still get data as “undefined”.

Try this:

handler: (data:string) => {
    console.log(data); //this should the selected value
}
2 Likes

Perfect, works! Many thanks!! Any idea how to force one of the Radio options to be the default option?

Hmm here is a complete example. Should work:

myAlert_show(){
    let myAlert = this.alertCtrl.create({
            title: 'Alert Title',
            subTitle: 'Alert subtitle...',
            enableBackdropDismiss: true ,
        message:'Ok, this is a very important alert message, you can call it VIAM :-) ...',
        buttons:[
    {
        text: 'OK',
        handler: data => {
            console.log('OK clicked. Data -> ' + JSON.stringify(data));
            },
        role: ''
    },
    {
        text: 'Abbrechen',
        handler: data => {
            console.log('Abbrechen clicked. Data -> ' + JSON.stringify(data));
            },
        role: 'cancel'
    }
],
    inputs:[
    {
        type: 'radio',
        id: 'opt1',
        name: 'opt1',
        'label': 'opt1',
        value: 'opt1',
        'checked': false
    },
    {
        type: 'radio',
        id: 'opt2',
        name: 'opt2',
        'label': 'opt2',
        value: 'opt2',
        'checked': false
    }
]
    });
    myAlert.present();
}
1 Like

You can add the checked: true to the inputs like this:

{
    type: 'radio',
    label: 'label 1',
    value: '0',
    checked: true
},
1 Like

many thanks!!!
works like a charm!!

yes, this works too, it was my bad the last time, forgot to choose an option!!

buddy, u know how can i put a code on the input of alertCtrl?
i need use mask on input…

trying to use this:

on alertctrl.