How to set default button in an Alert (Enter=OK)?

Is there a way to set a role on a button in an alert such that user pressing ENTER simulates a click on that button (e.g. “OK”, “Save”, etc…)

Mainly this seems important for cases where the alert has one or more input.

For example, let’s say you have [Rename Foobar] which pops an alert with an input field:

Foobar Name: [ ]
Cancel Rename

You would like the user to be able to type a name and hit ‘Enter’ while still in the input field.

role:‘ok’ does not seem to work

hi just do it like this and make the dynamic action inside your button code
/*

  • Show Alert Message
    */
    async presentAlert(header, msg) {
    let alert = await this.alertCtrl.create({
    header: header, message: msg, animated: true, backdropDismiss: true, cssClass: “”,
    buttons: [
    {
    text: ‘Cancel’,
    role: ‘cancel’,
    cssClass: ‘secondary’,
    handler: (blah) => {
    console.log(‘Confirm Cancel: blah’);
    }
    }, {
    text: ‘Okay’,
    handler: () => {
    console.log(‘Confirm Okay’);
    }
    }
    ]
    });
    await alert.present();
    }

I think I could have been more clear.
We are building a desktop app, and want it to be keyboard friendly.
So, in an alert with a text input, want to have the ENTER key event in that input act as “OK”.
Along the way, also noticed I needed to jump through hoops to set the focus to the input field as well;

Here is what I came up with.

 opts.inputs[0].id = this.inputID;
   
 return this.alertCtrl.create(opts)
    .then((a) => {
      if (this.inputID) {
        const elem = this.document.getElementById(this.inputID);
        if (elem) {
          // hack to set focus on the <input>
          setTimeout(() => { elem.focus(); }, 100);

          elem.onkeyup = (ev) => {
            if (ev.key === 'Enter') {
              doSomeAction();
              return this.alertCtrl.dismiss();
            }
          };
        }
      }

      return a.present();
2 Likes

Thank you for sharing your response, it really helped me!
It’s a shame Ionic misses these basic concepts/functionalities like a “confirm” role.
I’ve came across several nuisance like this, for basic stuff, that I had to patch an ugly javascript hack to do the job.