Becky
Becky

Reputation: 5585

val().replace in textarea

Is there a way prevent adding a newline if the current line is empty in a textarea? example:

Allowed:

The brown
candle

Prevent:

The brown
          // --> empty line break 
candle
          // --> empty line break 
          // --> empty line break 

Basically I want to avoid empty line breaks. How can I do this?

This is what I tried but no success.

$('textarea#comment').val( $('textarea#comment').val().replace(/\s*$/,"") );

Upvotes: 1

Views: 791

Answers (2)

Yoshi
Yoshi

Reputation: 54649

The following will prevent empty lines, while keeping the cursor at a somewhat sane position. Though you need to check selectionEnd and input-event support for your project.

$('.no-extra-lines').on('input', function () {
  var notAllowed = /(\r?\n){2,}/g, c = this.selectionEnd, len = this.value.length;

  if (notAllowed.test(this.value)) {
    this.value = this.value.replace(notAllowed, '$1');
    this.selectionEnd = c + this.value.length - len;
  }
});
<textarea class="no-extra-lines" rows="12" style="box-sizing: border-box; width: 100%">The brown
candle</textarea>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>

Upvotes: 3

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

you should check and replace current value of text-area on key up to achieve this as following :

$('textarea#comment').on('keyup', function() {
    $('textarea#comment').val($('textarea#comment').val().replace(/^(\r\n)|(\n\n)/,''));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="comment"></textarea>

Upvotes: 2

Related Questions