6

I have a Javascript function that is associated with an onChange event. I understand that some browsers support onPaste at either the document or an element level. Is there a way to determine if the onChange event was caused by a "paste" - I tried adding a global var that gets set when onPaste is fired, and then reset it at the end of my onChange routine, but there is no guarantee that the onPaste function gets called before the onChange.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JJSO
  • 61
  • 1
  • 2
  • The `change` event only fires when a text field is blurred. It's impossible to know what triggered it if multiple changes occurred. – eyelidlessness Dec 07 '10 at 08:29

4 Answers4

1

This worked fine for me:

<input type="text" onchange="ValueChanged(event, this);" onpaste="this.setAttribute('pasted', '1');"/>


<script type="text/javascript">
function ValueChanged(evt, sender) {
    var blnCameFromPaste = ((sender.getAttribute("pasted") || "") == "1");
    if (blnCameFromPaste)
        alert("changed by paste");
    else
        alert("changed without paste");
    sender.setAttribute("pasted", "0")
}
</script>
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1

You could use onKeyPress/onKeyUp/onKeyDown/onPaste instead of onChange.

Raphael Michel
  • 854
  • 1
  • 9
  • 18
  • 1
    And you can use the `input` event as well. And `input` is supported by all browsers except IE, which can be made to simulate it pretty effectively using the `propertychange` event. Other than capturing what key is pressed, the `input`/`propertychange` event does everything you'd need with the key events. – eyelidlessness Dec 07 '10 at 08:36
0

I don't think you'll be able to do this universally. See the current state of testing this feature.

One way to detect a paste would be to count the time between "keypresses" once a field has focus.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

Every time you see an onchange event compare the current length of the value of the field to the previous length, and the current time to the previous time. If the characters were entered faster than a person could conceivably type them, they must have been pasted.

bobpoekert
  • 934
  • 1
  • 11
  • 26
  • This could falsely detect a "paste" from a webdriver operating the page and inputting keystrokes faster than a human ever could. – Lucas Aug 02 '23 at 17:35