vincent
vincent

Reputation: 1313

clearing linebreaks from textarea

i'm trying to remove linebreaks when posting from word in a textarea. Atm this isnt working at all, eventhou i thought this should be a breeze. I'm sure i'm forgetting something small but i cant figure it out. This is the method that gets called on paste.

function cleanLineBreaks(el) {
    var editedText = $(el).val().replace(/(\r\n|\n|\r)/gm," ");
    $(el).val(editedText);
}

I created a fiddle to explain.

Just paste some text that has linebreaks in it, as you can see, the linebreaks arent cleaned

https://jsfiddle.net/gg56rw36/7/

Upvotes: 1

Views: 60

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You have to pass current object to cleanLineBreaks function.

Also, you need to bind onPaste event handler, not onclick.

<textarea onclick="cleanLineBreaks(this)"></textarea>

function cleanLineBreaks(el) {
    setTimeout(function(){
        var editedText = $(el).val().replace(/(\r\n|\n|\r)/gm," ");
        $(el).val(editedText);
    },0);
}
textarea {
  width: 400px;
  height: 400px;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea onPaste="cleanLineBreaks(this)"></textarea>

Upvotes: 2

Related Questions