Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading