Issue
I need to get all of the pasted string in input which has a maxLength attribute.
But in ‘onpaste’ event there is no property to get all of the pasted string.
For example, check below snippet with this string:
"AAAAA-BBBBB-BBBBB-BBBBB-BBBBB"
The output is : "AAAAA"
But I need all of the string.
const onPasteFn = (e) => {
setTimeout(() => document.getElementById("demo").innerHTML = e.target.value, 0)
}
<input type="text" maxLength="5" onpaste="onPasteFn(event)" />
<p id="demo"></p>
Solution
Consider using clipboardData
from the event, where you can use getData()
to grab the text that was pasted from the clipboard like so:
const onPasteFn = (e) => {
document.getElementById("demo").textContent = (e.clipboardData || window.clipboardData).getData('text');
}
<input type="text" maxLength="5" onpaste="onPasteFn(event)" />
<p id="demo"></p>
See example here from the docs. Note that the fallback of || window.clipboardData
is used for IE support.
Answered By – Nick Parsons
Answer Checked By – Willingham (BugsFixing Volunteer)