laboratorio caffeina

in few words, just developing

 

Utilizzare il Tab in una Textarea

Nel normale funzionamento di un form il tasto tab passa da un campo all'altro.

Capita però (come in questo blog) di dover dare la possibilità  a chi scrive di inserire del codice e tutti sappiamo quanto sia FONDAMENTALE l'indentazione per renderlo comprensibile.

O ci si affida all'intelligenza di chi scrive, sperando che utilizzi in modo coerente gli spazi o il copia e incolla, oppure si utilizza questa funzione (via l4x.org ):

JavaScript:
  1. function insertTab(event,obj) {
  2.     var tabKeyCode = 9;
  3.     if (event.which) // mozilla
  4.         var keycode = event.which;
  5.     else // ie
  6.         var keycode = event.keyCode;
  7.     if (keycode == tabKeyCode) {
  8.         if (event.type == "keydown") {
  9.             if (obj.setSelectionRange) {  // mozilla
  10.                 var s = obj.selectionStart;
  11.                 var e = obj.selectionEnd;
  12.                 obj.value = obj.value.substring(0, s) + "\t" + obj.value.substr(e);
  13.                 obj.setSelectionRange(s + 1, s + 1);
  14.                 obj.focus();
  15.             } else if (obj.createTextRange) {  // ie
  16.                 document.selection.createRange().text="\t"
  17.                 obj.onblur = function() { this.focus(); this.onblur = null; };
  18.             } else {
  19.                 // unsupported browsers
  20.             }
  21.         }
  22.         if (event.returnValue) // ie ?
  23.             event.returnValue = false;
  24.         if (event.preventDefault) // dom
  25.             event.preventDefault();
  26.         return false; // should work in all browsers
  27.     }
  28.     return true;
  29. }

HTML:
  1. <textarea onkeydown="return insertTab(event,this);" onkeyup="return insertTab(event,this);"  onkeypress="return insertTab(event,this);"  rows="30" cols="80"></textarea>

 
 

Commenta



 
Chiudi
E-mail It