Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste code from clipboard in multiple input fields

I was looking for Vanilla Javascript solution, of copy paste code into multiple input fields.

i have got solutions on internet but are jQuery based. This was jQuery Solution

<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">

I had copy this code from email, and past code on any input field, it will paste complete code one by one in each field. Then get this code verify with pre-saved code. Pasting and then collecting and verify code in vanilla JavaScript is what i am looking for.

like image 756
Arslan Ameer Avatar asked Oct 17 '25 14:10

Arslan Ameer


1 Answers

Here's one way to do it, it can easily be modified to work on specific text inputs, but as-is this ensures every text input on the page gets the same data from the clipboard.

Side note: querySelectorAll returns a nodelist instead of an array, you can use [].forEach.call to use an Array's forEach method in a nodelist.

// Listen to paste on the document
document.addEventListener("paste", function(e) {
  // if the target is a text input
  if (e.target.type === "text") {
   var data = e.clipboardData.getData('Text');
   // split clipboard text into single characters
   data = data.split('');
   // find all other text inputs
   [].forEach.call(document.querySelectorAll("input[type=text]"), (node, index) => {
      // And set input value to the relative character
      node.value = data[index];
    });
  }
});
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
like image 126
JKirchartz Avatar answered Oct 20 '25 05:10

JKirchartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!