Skip to content

Instantly share code, notes, and snippets.

@mnofresno
Created November 9, 2021 15:51
Show Gist options
  • Save mnofresno/ec6926e0f398436653945930e0965362 to your computer and use it in GitHub Desktop.
Save mnofresno/ec6926e0f398436653945930e0965362 to your computer and use it in GitHub Desktop.
This Gist is able to handle the paste event on an HTML page using data coming from Excel or google drive
<html>
<body>
<div id='editableDiv' contenteditable='true'>
<form>
<table id="tabla">
<tr>
<th>Campo 1</th>
<th>Campo 2</th>
<th>Campo 3</th>
</tr>
<tr>
<td><input id="campo11" type="text" placeholder="campo1" /></td>
<td><input id="campo21" type="text" placeholder="campo2" /></td>
<td><input id="campo31" type="text" placeholder="campo3" /></td>
</tr>
<tr>
<td><input id="campo12" type="text" placeholder="campo1" /></td>
<td><input id="campo22" type="text" placeholder="campo2" /></td>
<td><input id="campo32" type="text" placeholder="campo3" /></td>
</tr>
</table>
<script>
function handlePaste(e) {
var clipboardData, pastedData;
e.stopPropagation();
e.preventDefault();
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('text/plain');
console.log(pastedData);
var rows = pastedData.split('\n');
var indiceFila = 0;
var indiceColumna = 0;
rows.forEach(fila => {
var columna = fila.split('\t');
indiceFila = indiceFila + 1;
columna.forEach(contenidoCelda => {
indiceColumna = indiceColumna + 1;
var idCelda = "campo" + indiceColumna + indiceFila;
console.log(idCelda);
var inputCelda = document.getElementById(idCelda);
inputCelda.value = contenidoCelda;
});
indiceColumna = 0;
});
}
const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);
</script>
</form>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment