Say I copy
1 2 3 4
And then select an input field, when I paste it, it automatically puts 1 into the first field, 2 into the second field, 3 into the 3rd etc etc.
The values copied will separated by space, comma or a tab.
The form is simple html and I use PHP to insert into database, whatever language the solution is would be ok. I would image its jQUery, even direct me to a relevant jQuery plug in, if it exists.
Advertisement
Answer
I’ve commented the code line-by-line, hopefully that’s enough. I have to head to work and I’ll make any clarifying edits once I get there.
$(function(){ //run this on dom ready $('.paste-me').on('paste', function(e){ //add the paste event to all of the paste-me classes var data1 = e.originalEvent.clipboardData.items[0]; //get the data transfer item of hte original clipboard data event. if(data1.kind == 'string' && data1.type=='text/plain'){ //If it is a string and text/plain, move forward e.stopPropagation(); //Stop the propagtion of this event data1.getAsString(function(s){ //get the string contents of the clipboard item. s = s.split('t'); //split it by spaces $('.paste-me').each(function(i,item){ //loop through each .paste-me item $(item).val( s[i] || ''); //set the value from the split array, or an empty string if someone copy/pastes something too small to put a value in each item }); }); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/>
2020 Edit
Since jQuery has fallen largely out of usage, in favor of a framework such as Angular, Vue, or React, I felt that this answer needed a bit of updating.
Below is a 100% Vanilla JS version that will work with the given HTML. Logically it follows the same steps as above, I just renamed some of the variables for readability. If you have any questions just ask.
document.addEventListener('DOMContentLoaded', () => { const pasteMes = document.querySelectorAll('.paste-me'); pasteMes.forEach(input => { input.addEventListener('paste', e => { const data = e.clipboardData.items[0]; if(data.kind == 'string' && data.type == 'text/plain') { data.getAsString(str => { str.split(/s/).forEach((v, ind) => { pasteMes[ind] && (pasteMes[ind].value = v || ''); }) }); } }); }); });
<input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/> <input class="paste-me" name="paste_me[]" type="text"/>