Skip to content Skip to sidebar Skip to footer

Make Input Element (type="text") Handle Multiple Lines Of Text

I've created a form with an input, but the box only handles text in a single row. I would like to style it so that the input field is similar to that of Twitter's, where the box it

Solution 1:

You need to use an HTML <textarea> element.

From MDN:

<textarea>

The HTML <textarea> element represents a multi-line plain-text editing control.

Using <input> for multiline text is not possible natively and, if hacked, would be invalid HTML.

HTML5 spec:

4.10.5.1.2 Text (type=text) state and Search state (type=search)

The input element represents a one line plain text edit control for the element's value.

(emphasis mine)


Twitter input box

You mention you want the textarea to resemble Twitter's (auto-resize / no scrollbar). Consider this option and the following SO posts:

Autosize

A small, stand-alone script to automatically adjust textarea height.

Solution 2:

Use TextArea.Alter rows and columns attribute according to requirement.

<textareaclass="input"rows="10"cols="10">Some text here</textarea>

To add the hover effect and change the box size , use css. Assign a normal height and width, and change that on focus.

.input:focus {
    height:300px;
}
.input{
    width:500px;
    height:200px;
}

Solution 3:

Use <div contenteditable="true"> (supported well) with storing to <input type="hidden">.

HTML:

<div id="multilineinput" contenteditable="true"></div>
<input type="hidden"id="detailsfield" name="detailsfield">

js (using jQuery):

$("#multilineinput").on('keyup',function(e) {   
    $("#detailsfield").val($(this).text()); //store content to input[type=hidden]
});

if anyone wanted to use this for wrapping a single line and using enter to submit or move on in the form, here is what to add:

$("#multilineinput").on('keypress',function(e) {    
    if(e.which == 13) { //on enter
        e.preventDefault(); //disallow newlines     // here comes your code to submit
    }
});

Post a Comment for "Make Input Element (type="text") Handle Multiple Lines Of Text"