Reputation: 461
I am trying to add 4 spaces to my textarea.
However, it only adds 1 space.
$(document).delegate('#test', '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;
$(this).val($(this).val().substring(0, start)
+ " " + " " + " " + " "
+ $(this).val().substring(end));
$(this).get(0).selectionStart =
$(this).get(0).selectionEnd = start + 1;
}
});
Edit:
I've already tested
and it gets outputted as is " " does output: " " to the tetarea.
How can I force it to add 4 spaces?
Upvotes: 2
Views: 2652
Reputation: 1457
$("textarea").on('keydown', function(e) {
if(e.keyCode == 9) {
e.preventDefault();
for(var i=0; i<4; i++) {
var start = this.selectionStart,
end = this.selectionEnd,
value = $(this).val();
$(this).val(value.substring(0, start)
+ " "
+ value.substring(end));
this.selectionStart = this.selectionEnd = start + 1;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="30" rows="10"></textarea>
Upvotes: 3
Reputation: 461
One solution is to call a function four times.
$(document).delegate('#code', 'keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
add_space();
add_space();
add_space();
add_space();
}
});
function add_space()
{
$code = $("#code");
var start = $code.get(0).selectionStart;
var end = $code.get(0).selectionEnd;
$code.val($code.val().substring(0, start)
+ " "
+ $code.val().substring(end));
$code.get(0).selectionStart =
$code.get(0).selectionEnd = start + 1;
}
Upvotes: 0
Reputation: 3287
$(document).delegate('#test', '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;
$(this).val($(this).val().substring(0, start)
+
+ $(this).val().substring(end));
$(this).get(0).selectionStart =
$(this).get(0).selectionEnd = start + 1;
}
});
Upvotes: 0