How to get selected text from textarea (javascript)

actually did as in the answer to the above question. But not getting in the firefox returns null I would like an implementation on jQuery. According to Google, I did not find this, the logic is in principle simple to determine the beginning of the selected area and the end, and by cutting the text to get the selected fragment. The task is basically trivial and is there no such function in jQuery?

ps I'm a php programmer for this in jQuery is not strong.

    1 answer 1

    [Offtop] Pure javscript:

     function gettext(area) { // all and IE9+ if ('selectionStart' in area) { var len = area.value.length, sp = Math.min(area.selectionStart, len), // IE bug ep = Math.min(area.selectionEnd, len); // IE bug return area.value.substring(sp, ep); } // IE9- if (document.selection && document.selection.createRange) { area.focus(); var sel = document.selection.createRange(); return sel.text; } return false; } 
     <div><input type="button" value="Жми" onclick="alert('Выделенный текст: \'' + gettext(document.getElementById('myText')) + '\'');return false;"></div> <textarea rows="10" cols="80" id="myText"></textarea> 

    • I solved the issue with github.com/localhost/jquery-fieldselection and the getSelection function and everything seems to work! but thanks anyway. - Naumov
    • interesting if ('selectionStart' in area) construction if ('selectionStart' in area) explain what it means - MaximPro
    • @MaximPro, checks if there is a property called selectionStart in the object pointed to by the area variable (in this case in textarea ). - Visman
    • aha clear, thanks - MaximPro