2

I want to empty an alert input if the user tried to paste a string in the textbox. This is my code:

openManualEdit () {
  let myAlert = this.alertCtrl.create({
      title: 'Ingreso Manual',
      message: 'Ingresa el código de barra en los campos debajo.',
      inputs: [
        {
          name: 'serial',
          placeholder: 'Número de serie',
          id: 'txtSerial'
        },
        {
          name: 'serial_confirm',
          placeholder: 'Confirma el número de serie',
          id: 'txtSerialConfirm'
        }
      ],
      buttons: [
        {
          text: 'Cancel'
        },
        {
          text: 'Continue',
          handler: (data) => {
            console.log(data);
        }
      }
    ]
  });
  myAlert.present().then(() => {
    // Empty textbox if user tries to paste
    document.getElementById('txtSerial').addEventListener('paste', function (event) {
      console.log(event);
      (<HTMLInputElement>event.target).value = '';
    });

 // Empty textbox if user tries to paste
 document.getElementById('txtSerialConfirm').addEventListener('paste', function (event) {
      // console.log(event);
      (<HTMLInputElement>event.target).value = '';
    });
  });
}

So far I'm detecting the paste event, but the code to empty the textbox isn't working. I've also tried using:

  • document.getElementById('txtSerial').value = '';
  • document.getElementById('txtSerial')["value"] = '';
  • event.srcElement["value"] = '";

But none of these seem to work. Any help is greatly appreciated.

Brian Moreno
  • 977
  • 4
  • 11
  • 39

1 Answers1

1

You can just use event.preventDefault() inside the event listeners. That will not allow pasting.

document.getElementById('txtSerial').addEventListener('paste', function (event) {
  console.log(event);
  event.preventDefault();
});

DEMO

AT82
  • 71,416
  • 24
  • 140
  • 167