patriciasmh
patriciasmh

Reputation: 350

How to create single-line text input field?

I have contenteditable input field on my web page. What do I need to do to make it transform multi-line text into single-line, for example just like google does if you copy large amount of text into the search field?

Example - I copy such text:

This is Random text, lalalalalalala
and it's multi-line,
but that's just now what I want.

And when I paste it into my contenteditable input field, I want to get:

This is Random text, lalalalalalala and it's multi-line, but that's just now what I want.

-> entire text in one row

Upvotes: 1

Views: 11807

Answers (4)

patriciasmh
patriciasmh

Reputation: 350

Use the following CSS on the element:

white-space:nowrap;

Upvotes: 2

Moob
Moob

Reputation: 16184

Use a text input. This is single line text field and will automatically remove line-breaks.

<input name="mySingleLineTextField" type="text" />

If you must use a textarea then you can easily format its value to remove tabs and line-breaks with a little bit of JavaScript:

<textarea name="myMultiLineTextFieldWithFormattingRemoved" onchange="this.value=this.value.replace(/([\n\r\t]+)/g, ' ')"></textarea>

eg: http://jsfiddle.net/z2rmxj4j/

As its not good form to put your scripts inline here's a little example that listens for a keyup event on all textareas that have the class 'nobreaks':

(function(){
    //select all textareas having the class of 'nobreaks'
    var elems = document.querySelectorAll("textarea.nobreaks");
    //for each element in our collection
    for(i=0; i<elems.length; i++){
        //attach a function to the keyup event
        elems[i].onkeyup = function(){
            this.value=this.value.replace(/([\n\r\t\s]+)/g, ' ');
        }
    }
})()
pre {color:grey}
input, textarea {display:block; width:300px; margin:10px;}
.nobreaks {}
.nowrap {white-space:nowrap;}
<pre>This is Random text, lalalalalalala
and it's multi-line,
but that's just now what I want.
</pre>

<input type="text" value="Will replace line-breaks, text cannot wrap." />
<textarea>Default. 
Wont replace line-breaks and text can wrap.</textarea>
<textarea class="nobreaks">Will replace line-breaks but text can still flow/wrap.</textarea>
<textarea class="nobreaks nowrap">Will replace line-breaks and prevent the text from wrapping.</textarea>

See https://developer.mozilla.org/en/docs/Web/HTML/Element/Input for more info on the input types.

Upvotes: 1

Iglo
Iglo

Reputation: 706

var text = "This had line\n breaks\n in it.";

text = text.replace(/(\r\n|\n|\r)/gm,"");

alert(text);

Upvotes: 0

Ahs N
Ahs N

Reputation: 8366

This is how I did it:

$('#paste').click(function(){
    $(this).html('');
});
$('#paste').focusout(function(){
    $(this).html($(this).text().replace('/n', ''));
});

Have a look at the full JSFiddle code demo

Upvotes: 1

Related Questions