John Svensson
John Svensson

Reputation: 461

Add Spaces to a Textarea

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

Answers (4)

iceMan33
iceMan33

Reputation: 369

Just use non-breakable spaces:   instead of regular spaces.

Upvotes: 0

Pik_at
Pik_at

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

John Svensson
John Svensson

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

Red2678
Red2678

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)
        + &nbsp;&nbsp;&nbsp;&nbsp;
        + $(this).val().substring(end));

        $(this).get(0).selectionStart =
        $(this).get(0).selectionEnd = start + 1;
}

});

Upvotes: 0

Related Questions