JS onpaste event should run a code and not paste

I have a code that I want to run whenever a paste event is being triggered on the page.

The code should take all the data from the clipboard and should paste it value by value in different fields in the form.

The issue is that the first field, where the paste event is being done, gets all the values instead of the first of the list.
All the other fields in the Form get populated correctly.

Pls find attached the code and a screenshot,

thanks for your help

document.addEventListener('paste', e=>{
    let data = e.clipboardData.getData('text/plain');
    let id = e.target.id;
    let id_ex = id.slice(0,2);
    var fill_array =[];
    var line = Number(id.slice(2,4));
    
  if (id_ex == "SK" || "DE" || "QT"){

    var splitter = data.split(/\r?\n/);
    var len = splitter.length;
  
    for (i=0;i<len;i++){
  
        if(splitter[i] == ""){}

          else{fill_array.push(splitter[i]);}
          }
    

    for (q=0;q<fill_array.length;q++){
      var lin = line + q;
      var id_to_fill = id_ex+lin  ;
      document.getElementById(id_to_fill).value = fill_array[q];
    }
  
    document.getElementById(id).value = fill_array[0];
   }



  else{}

});

enter image description here

>Solution :

To prevent paste action you should event.preventDefault()

document.addEventListener('paste', e => {
   if ( !isEventIDoHandle(e) ) return; // will paste
   e.preventDefault(); // will not paste
   handlePasteEventAsIWant(e);
})

Leave a Reply