09-05-2026

Como tabular el texto de un textarea usando el tabulador en javascript

Por defecto, al pulsar el tabulador dentro de un "textarea" en una página , el navegador cambia el foco al siguiente elemento del formulario. Pero es muy común querer que el tabulador inserte una tabulación (espacios o carácter "\t") dentro del texto. En el ejemplo se pone el código para tabular varias líneas (seleccionándolas):

const textarea = document.getElementById('id-textarea');

textarea.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();

const start = this.selectionStart;
const end = this.selectionEnd;
const selectedText = this.value.substring(start, end);
const tab = ''; // o '\t'

// Si hay texto seleccionado
if (selectedText.includes('\n')) {
  // Modo multilínea: indentar todas las líneas
  const lines = selectedText.split('\n');
  const indentedLines = lines.map(line => tab + line);
  const indentedText = indentedLines.join('\n');

  this.value = this.value.substring(0, start) + 
 indentedText + 
 this.value.substring(end);

  this.selectionStart = start;
  this.selectionEnd = start + indentedText.length;
} 
else {
  // Modo una sola línea
  this.value = this.value.substring(0, start) + 
 tab + 
 this.value.substring(end);

  this.selectionStart = this.selectionEnd = start + tab.length;
}
}
});