Format text in a ?

If you need to customize your textarea, reproduce its behavior using another element (like a DIV) with the contenteditable attribute. It’s more customizable, and a more modern approach, textarea is just for plain text content, not for rich content. <div id=”fake_textarea” contenteditable></div> The scrollbars can be reproduced with the CSS overflow property. You can use … Read more

Count characters in textarea

What errors are you seeing in the browser? I can understand why your code doesn’t work if what you posted was incomplete, but without knowing that I can’t know for sure. You should probably clear the charNum div, or write something, if they are over the limit. function countChar(val) { var len = val.value.length; if … Read more

Cursor position in a textarea (character index, not x/y coordinates)

Modified BojanG’s solution to work with jQuery. Tested in Chrome, FF, and IE. (function ($, undefined) { $.fn.getCursorPosition = function() { var el = $(this).get(0); var pos = 0; if(‘selectionStart’ in el) { pos = el.selectionStart; } else if(‘selection’ in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart(‘character’, -el.value.length); pos = … Read more

How to insert text into the textarea at the current cursor position?

Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well) function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA and others else if (myField.selectionStart || myField.selectionStart == ‘0’) { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + … Read more

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method. .text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other: var t=”<textarea>”; console.log($(t).text(‘test’).val()); // Prints test console.log($(t).val(‘too’).text(‘test’).val()); // Prints too … Read more

Insert text into textarea with jQuery

I like the jQuery function extension. However, the this refers to the jQuery object not the DOM object. So I’ve modified it a little to make it even better (can update in multiple textboxes / textareas at once). jQuery.fn.extend({ insertAtCaret: function(myValue){ return this.each(function(i) { if (document.selection) { //For browsers like Internet Explorer this.focus(); var sel … Read more