Rectangle 27 60

jQuery solution adjust the css to match your requirements

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}
// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

I've created a fiddle with the absolute minimum styling as a starting point for your experiments... http://jsfiddle.net/53eAy/951/

This is good, but I would add overflow-y: hidden; to the css to prevent the scroll bar from briefly flashing when resize occurs.

+1 for providing solutions for jQuery 1.6 and below and jQuery 1.7+!

$('textarea.auto-resize').on('change cut paste drop keyup', function(){...})

javascript - Creating a textarea with auto-resize - Stack Overflow

javascript resize textarea height
Rectangle 27 60

jQuery solution adjust the css to match your requirements

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}
// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

I've created a fiddle with the absolute minimum styling as a starting point for your experiments... http://jsfiddle.net/53eAy/951/

This is good, but I would add overflow-y: hidden; to the css to prevent the scroll bar from briefly flashing when resize occurs.

+1 for providing solutions for jQuery 1.6 and below and jQuery 1.7+!

$('textarea.auto-resize').on('change cut paste drop keyup', function(){...})

javascript - Creating a textarea with auto-resize - Stack Overflow

javascript resize textarea height
Rectangle 27 31

The problem is that the Enter keypress is not being suppressed and is doing its usual browser behaviour (i.e. adding a line break). Add return false to the end of your keypress handler to prevent this.

$("#area").keypress(function (e) {
    if (e.keyCode != 13) return;
    var msg = $("#area").val().replace(/\n/g, "");
    if (!util.isBlank(msg))
    {
        send(msg);
        $("#area").val("");
    }
    return false;
});

replace should be replace(/\n/g, ""); replace("\n", "") will only delete the first new line

@Orlando: That line of code came straight from the question so it's possible that's replacing just the first line break is what the OP intended, but I agree it's unlikely.

To be consistent with all the line breaks, /(\r?\n|\r\n?)/ is best.

val()

javascript - Remove line break from textarea - Stack Overflow

javascript jquery html textarea
Rectangle 27 18

This function expects first parameter to be reference to your textarea and second parameter to be the line number

function selectTextareaLine(tarea,lineNum) {
    lineNum--; // array starts at 0
    var lines = tarea.value.split("\n");

    // calculate start/end
    var startPos = 0, endPos = tarea.value.length;
    for(var x = 0; x < lines.length; x++) {
        if(x == lineNum) {
            break;
        }
        startPos += (lines[x].length+1);

    }

    var endPos = lines[lineNum].length+startPos;

    // do selection
    // Chrome / Firefox

    if(typeof(tarea.selectionStart) != "undefined") {
        tarea.focus();
        tarea.selectionStart = startPos;
        tarea.selectionEnd = endPos;
        return true;
    }

    // IE
    if (document.selection && document.selection.createRange) {
        tarea.focus();
        tarea.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
        return true;
    }

    return false;
}
var tarea = document.getElementById('myTextarea');
 selectTextareaLine(tarea,3); // selects line 3
window.getSelection().removeAllRanges()

javascript - How to select line of text in textarea - Stack Overflow

javascript jquery textarea
Rectangle 27 28

<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
$(document).ready(function(){

    var lines = 10;
    var linesUsed = $('#linesUsed');

    $('#countMe').keydown(function(e) {

        newLines = $(this).val().split("\n").length;
        linesUsed.text(newLines);

        if(e.keyCode == 13 && newLines >= lines) {
            linesUsed.css('color', 'red');
            return false;
        }
        else {
            linesUsed.css('color', '');
        }
    });
});

Samuel Liew, thank you so very much! I'm sure this will be helpful to a lot of people.

The return false does not seem to be working when I paste in a large number of lines. Is there a way this can be modified to ensure a user cannot submit the form if the number of allowed lines has been exceeded?

You could use the 'paste' event on the text area

javascript - Limit number of lines in textarea and Display line count ...

javascript jquery html validation textarea
Rectangle 27 18

The default behaviour of the Enter key in a textarea is to add a new line. You need to prevent this action occurring within the createOnEnter method, add e.preventDefault(); after matching the key press as the Enter key.

createOnEnter: function(e) {
          if (e.keyCode == 13) {
            e.preventDefault();
            items.create(this.newAttributes());
            $("#create-item :input").val('');
            $("#create-item :input")[0].focus();
          };
        }

In case your using IE you need to use event.returnValue = false; instead of e.preventDefault();

My God, that has been bugging me for a good 20 minutes now. Would never have guessed it either, thank you so much!

me too, I have been bugging for a while, it's only a simple e.preventDefault(); to stop the new line from enter, I knew there is an easy way to do that, Thanks for the answer here!

javascript - How do I remove the extra newline in textarea after clear...

javascript jquery javascript-events textarea newline
Rectangle 27 4

$('input[type=button]').click(function () {
    var html = "";
    var lines = $('#hi').val().split('\n');
    for (var i = 0; i < lines.length; i++) {
        //code here using lines[i] which will give you each line
        html += lines[i];
        html += ",";
    }
    html = html.substring(0,html.length-1);
    $("#inthis").html(html);
});

javascript - Reading text in textarea line by line - Stack Overflow

javascript jquery html textarea
Rectangle 27 2

Careful, they might have issues with different browsers. You can set a predefined line height or font size that you later use to obtain caret position.

I didn't tested any of the methods but let's assume that the function used to get caret position (in pixels) returns the y component with respect to the bottom of the caret. You specify a line height of 15 px. Let's say method returns (20, 45). Current line = y/15 = 45/15 = 3

JS Fiddle to demonstrate how it can be done based on Dan's solution: Current line from caret coordinates

I added a span where the current line is displayed. Sadly, my tests on Chrome shows that this is not 100% accurate: When you select third line with mouse it says you are on 4th line.

Line:
<span id="line">0</span>

At the end of the update function (in HTML section) I added the following line:

//24 is the top padding of the textarea
//16 is the line-height
line.innerText = (coordinates.top - 24) / 16;

javascript - Is the caret on the first line of the textarea? On the la...

javascript jquery html dom textarea
Rectangle 27 19

I've done a fair amount of work on this and posted a function for getting caret/selection position in textareas on Stack Overflow several times. Unlike pretty much every other code to do this out there, it works properly with line breaks in IE < 9.

And here's a link to a jQuery plug-in I've written that includes this function and other selection-related textarea functions:

javascript - How do you get the cursor position in a textarea? - Stack...

javascript jquery html input textarea
Rectangle 27 1

See this Fiddle from this answer. That increases the height of the textarea based on the number of lines.

Copied the code from the answer below:

<p>Code explanation: <a href="http://www.impressivewebs.com/textarea-auto-resize/">Textarea Auto Resize</a></p>

<textarea id="comments" placeholder="Type many lines of texts in here and you will see magic stuff" class="common"></textarea>
/*global document:false, $:false */
var txt = $('#comments'),
    hiddenDiv = $(document.createElement('div')),
    content = null;

txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common');

$('body').append(hiddenDiv);

txt.on('keyup', function () {

    content = $(this).val();

    content = content.replace(/\n/g, '<br>');
    hiddenDiv.html(content + '<br class="lbr">');

    $(this).css('height', hiddenDiv.height());

});
body {
     margin: 20px;
}

p {
    margin-bottom: 14px;
}

textarea {
    color: #444;
    padding: 5px;
}

.txtstuff {
    resize: none; /* remove this if you want the user to be able to resize it in modern browsers */
    overflow: hidden;
}

.hiddendiv {
    display: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word; /* future version of deprecated 'word-wrap' */
}

/* the styles for 'commmon' are applied to both the textarea and the hidden clone */
/* these must be the same for both */
.common {
    width: 500px;
    min-height: 50px;
    font-family: Arial, sans-serif;
    font-size: 13px;
    overflow: hidden;
}

.lbr {
    line-height: 3px;
}

javascript - Automatically resize text area based on content - Stack O...

javascript jquery css3 textarea
Rectangle 27 3

Having that 15 is the line height, this works (tested in firefox):

$("textarea").click(function (evt) {
  cursor_position = evt.pageY - $('textarea').offset().top;
  if (cursor_position <= 15) {
    alert("first line");
  } else {
    alert("other line");
  }
});

This is an excellent solution, but I was looking for the text cursor, not the mouse cursor! I'm sorry - this is my fault, my question was unnecessarily ambiguous!

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Test if cursor is on the first line in a textarea (with s...

javascript jquery html dom textarea
Rectangle 27 3

I only know of one "working method". The method requires use of textarea's "cols" attribute. Long story short, set the cols to the width you want, then divide the cursor position and floor it to see if it is less than 1, thus it = line 1!

$("textarea").live("keyup", function(e) {
    if ($("textarea").attr("cols")) {
        var cols = parseInt($("textarea").attr("cols")),
            curPos = $('textarea').prop("selectionStart"),
            result = Math.floor(curPos/cols);
        var msg = (result < 1) ? "Cursor is on the First line!" : "Cursor is on the line #"+(result+1);
        console.log($("p").text(msg).text());
    };
});

however, this may still require some wired math as some col sizes may still say "line 2" when the cursor is simply at the END of line one (which technically would still be right since any character would drop to line 2)

Thanks SpYk3HH. This is interesting, though the math seems to not be working correctly in the jsFiddle.

Yea, I did notice one issue, in that if the chars don't go near end of line u get a misread, i'm thinking, get back to this shortly ...

Nice solution, I didn't know the selectionStart property. BTW, it is not treating enter characters!

javascript - Test if cursor is on the first line in a textarea (with s...

javascript jquery html dom textarea
Rectangle 27 2

To preserve newlines that are coming from a database or whatever, replace the newline characters with the HTML entity for a line feed:

base = base.replace("\n", '&#xA;');
$('#image_Basename').append(base);

If you're trying to append each string with a newline at the end, just concatenate it onto the string:

Also, you're using split on the textarea jQuery element, which doesn't make sense as it is an object not a string.

unfortunately, this didn't work ! I'm storing it in to the database, and after retrieving it, I get the mixed value

$('#image_Basename').append(base + '&#xA;');

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - append text to a textarea with line breaks - Stack Overfl...

javascript jquery append textarea line-breaks
Rectangle 27 1

Unfortunately multi-line placeholders are not supported as a rule. Chrome does allow for newline characters, but support across platforms can be spotty. The recommended course of action would be to create shorter, single-line placeholders. If you absolutely need a multi-line placeholder, you can try this:

<textarea style='white-space:pre;' placeholder='Line 1

Line2'></textarea>

By adding the css attribute white-space:pre, you force the textarea to treat the placeholder text as preformatted text. Again, though, support is spotty.

javascript - How to add multi line place holder text in textarea? - St...

javascript jquery textarea placeholder
Rectangle 27 1

Previous answers don't handle splitting the current value of the textarea and simply appends a new line character. The following stops the event from bubbling up to the form and still allows typical textarea behavior on 'enter'.

$('textarea').keydown(function(event) {
  if (event.keyCode === 13) {
    event.stopPropagation();
  }
});

javascript - Add new line character to textarea instead of submitting ...

javascript jquery html textarea
Rectangle 27 1

Previous answers don't handle splitting the current value of the textarea and simply appends a new line character. The following stops the event from bubbling up to the form and still allows typical textarea behavior on 'enter'.

$('textarea').keydown(function(event) {
  if (event.keyCode === 13) {
    event.stopPropagation();
  }
});

javascript - Add new line character to textarea instead of submitting ...

javascript jquery html textarea
Rectangle 27 1

In Chrome, you cant resize a textarea to a size smaller than its original height and width.

This is actually specified in the W3C specifications, which disctates browsers can defined such characteristics:

The user agent may restrict the resizing range to something suitable, such as between the original formatted size of the element, and large enough to encompass all the element's contents.

That said, this has also been raised as a bug in Chrome

You can, however, override this using Javascript, simply give your textarea the class resizable and add the below to your page:

function resizableStart(e){
    this.originalW = this.clientWidth;
    this.originalH = this.clientHeight;
    this.onmousemove = resizableCheck;
    this.onmouseup = this.onmouseout = resizableEnd;
}
function resizableCheck(e){
    if(this.clientWidth !== this.originalW || this.clientHeight !== this.originalH) {
        this.originalX = e.clientX;
        this.originalY = e.clientY;
        this.onmousemove = resizableMove;
    }
}
function resizableMove(e){
    var newW = this.originalW + e.clientX - this.originalX,
        newH = this.originalH + e.clientY - this.originalY;
    if(newW < this.originalW){
        this.style.width = newW + 'px';
    }
    if(newH < this.originalH){
        this.style.height = newH + 'px';
    }
}
function resizableEnd(){
    this.onmousemove = this.onmouseout = this.onmouseup = null;
}
var els = document.getElementsByClassName('resizable');
for(var i=0, len=els.length; i<len; ++i){
    els[i].onmouseover = resizableStart;
}

javascript - Resize textarea programmatically without modifying min-si...

javascript jquery css html5 textarea
Rectangle 27 1

$("textarea").on('input',function(){
    var currentPosition = this.selectionStart;
    var trimmedInput = $.map($(this).val().split("\n"), function(line){
        return $.trim(line).substring(0,10);
    });

    $("textarea").val(trimmedInput.join("\n"));
     setSelectionRange(this, currentPosition, currentPosition);

});

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

You are welcome :)

javascript - Trim and edit each line of textarea while user is typing ...

javascript jquery html textarea
Rectangle 27 4

// See http://mathiasbynens.be/notes/showdown-javascript-jquery for a plain JavaScript version as well
$(function() {
 // When using more than one `textarea` on your page, change the following line to match the one youre after
 var $textarea = $('textarea'),
     $preview = $('<div id="preview" />').insertAfter($textarea),
     converter = new Showdown.converter();
 $textarea.keyup(function() {
  $preview.html(converter.makeHtml($textarea.val()));
 }).trigger('keyup');
});

jquery - Javascript to convert Markdown/Textile to HTML (and, ideally,...

javascript jquery markdown textile