Reputation: 3578
I have created a form for a competition. I have 4 text boxes that take 4 characters each which are then combined to create a 16 digit code. This is all working fine.
Example Code: LAME DKAJ XWNS YXRZ
My issue is, I want to monitor paste events (for if the user decides to paste the code in). However, the 16 digit codes at their source contain spaces - my aim is to split the code at these spaces to give me 4 groups of 4 characters and automatically fill the boxes.
However, when using the paste event, I experience unexpected behaviour. For example, the first time I paste text in to the box, a console.log of the value returns a blank string. The second paste logs what should have been in the first and so on. This indicates to me that it's logging at the beginning of the paste event, rather than after the code has been pasted in to the text box. Am I doing this wrong, or is this intended?
If this is the intended behaviour of the paste event, how can I capture the text in the box after the paste event has finished?
https://jsfiddle.net/h4w946js/ (check the console)
// JS CODE
function splitCode(){
var input = document.getElementById('part1');
input.addEventListener('paste', function(){
console.log(this.value);
})
}
Upvotes: 0
Views: 47
Reputation: 66590
to get pasted text use this code:
input.addEventListener('paste', function(e) {
if (window.clipboardData && window.clipboardData.getData) { // IE
console.log(window.clipboardData.getData('Text'));
} else if (e.clipboardData && e.clipboardData.getData) { // other browsers
console.log(e.clipboardData.getData('text/plain'));
}
});
Upvotes: 2