Sto tentando di inserire quattro spazi quando si preme il tasto Tab. Stavo usando il seguente codice (vedi spaces = "\t"
), ma quando lo passo a spaces = " "
viene inserito solo uno spazio quando premo il tasto tab. Ho anche provato "" + "" + "" + " ":Inserire quattro spazi anziché la scheda
$(function() {
$('textarea').keydown(function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var start = $(this).get(0).selectionStart;
var end = $(this).get(0).selectionEnd;
// set textarea value to: text before caret + tab + text after caret
spaces = "\t"
$(this).val($(this).val().substring(0, start)
+ spaces
+ $(this).val().substring(end));
// put caret at right position again
$(this).get(0).selectionStart =
$(this).get(0).selectionEnd = start + 1;
}
});
});
NOTA: Questo è quello di inserire spazi in un browser-based textarea/ide.
per me funziona in Chrome/IE9/FF32 - http://jsfiddle.net/17auq970/ - quale browser stai usando? – Rhumborl
Non esattamente correlati, ma il controllo 'e.which' non è necessario, jQuery normalizza la proprietà per te (' which'). – Teemu
Grazie a @Teemu buon pensiero – maudulus