How to get the start and end points of selection in text area?

Discussion in 'JavaScript' started by nayana4u, Jun 17, 2010.

  1. #1
    i want to get the cursor start and end position of a selected range in a text-field or text-area. i tried lot of functions in various forums. but when the last character of the selection is a new line character JavaScript ignore it in IE6. any one having idea ?

    thank you
    Nayana Adassuriya
     
    nayana4u, Jun 17, 2010 IP
  2. netload

    netload Member

    Messages:
    105
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    28
    #2
    function get_selection(textarea) {
    	// Code for IE
    	if (document.selection) {
    	    textarea.focus();
    		return document.selection.createRange().text;
    	} else {
    	// Code for Mozilla Firefox
    		var len = textarea.value.length;
    	    var start = textarea.selectionStart;
    		var end = textarea.selectionEnd;
    		var scrollTop = textarea.scrollTop;
    		var scrollLeft = textarea.scrollLeft;
            return textarea.value.substring(start, end);
    	}
    }
    Code (markup):
     
    netload, Jun 17, 2010 IP