How to access values in a Radio Alert


#1

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();

#2

Try to change your handler like this:

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

#3

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


#4

Did you add data in handler callback?


#5

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


#6

Try this:

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

#7

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


#8

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

#9

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

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

#10

many thanks!!!
works like a charm!!


#11

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


#12

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


#13

trying to use this:

on alertctrl.