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:
-
function insertTab(event,obj) {
-
var tabKeyCode = 9;
-
if (event.which) // mozilla
-
var keycode = event.which;
-
else // ie
-
var keycode = event.keyCode;
-
if (keycode == tabKeyCode) {
-
if (event.type == "keydown") {
-
if (obj.setSelectionRange) { // mozilla
-
var s = obj.selectionStart;
-
var e = obj.selectionEnd;
-
obj.value = obj.value.substring(0, s) + "\t" + obj.value.substr(e);
-
obj.setSelectionRange(s + 1, s + 1);
-
obj.focus();
-
} else if (obj.createTextRange) { // ie
-
document.selection.createRange().text="\t"
-
obj.onblur = function() { this.focus(); this.onblur = null; };
-
} else {
-
// unsupported browsers
-
}
-
}
-
if (event.returnValue) // ie ?
-
event.returnValue = false;
-
if (event.preventDefault) // dom
-
event.preventDefault();
-
return false; // should work in all browsers
-
}
-
return true;
-
}
HTML:
-
<textarea onkeydown="return insertTab(event,this);" onkeyup="return insertTab(event,this);" onkeypress="return insertTab(event,this);" rows="30" cols="80"></textarea>

Commenta