Lajos Arpad
Lajos Arpad

Reputation: 76551

Onpaste is only triggered by keyboard paste

I have this code:

<input type="text" id="point-setter-input" onkeyup="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" onpaste="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" value="0">
<span class="api command initialized" data-command-name="SetPoints" data-events="click" data-container="#popup-content" id="point-setter-span" data-data="data=3">Pontok Mentése</span>

Whenever the value of the input changes via onkeyup, data-data of the span is getting that value if it happens to be a number. However, onpaste will never run. If I paste via the keyboard, then data-data of the span will be successfully updated, but this happens only because of my onkeyup, that is, if I do not have that attribute, even pasting with keyboard will not run. Why is onpaste disfunctional in my case? I have checked this in Chrome and Firefox.

EDIT

It turns out that onpaste is executed, but value is not the pasted text. I think an ugly solution is needed here, involving setTimeout.

Upvotes: 0

Views: 390

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76551

I have solved this using setTimeout, so the value was changed when I used it:

<input type="text" id="point-setter-input" onkeyup="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" onpaste="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" value="0">

Upvotes: 0

Kaiido
Kaiido

Reputation: 136707

The paste event fires before the <input>'s value is set, otherwise you couldn't prevent its default behavior (which is to set the <input>'s value).

So when you check if(!isNaN(this.value)), the new value contained in the paste event is still not set.

To workaround this, simply listen to the input event, which will get fired in any case.

var inp = document.getElementById('inp');
inp.onpaste = function() {
  console.log('paste', this.value);
};
inp.oninput = function() {
  console.log('input', this.value);
}
<input type="text" id="inp">

Upvotes: 1

Related Questions