2

I'm using the following function to get selected text and it works very well in all major browsers but it doesn't work correctly in IE before version 9!

function getSelected() {
    var t = '';
 if (window.getSelection) {
     t = window.getSelection();
} else if (document.getSelection) {
    t = document.getSelection();
    t = t.toString();
} else if (document.selection) {
    t = document.selection.createRange();
    t = t.text;
}
    return t;
}

var txt = getSelected();

The problem here that with IE before version 9 it doesn't store any text in the variable "txt"

Develop Smith
  • 146
  • 1
  • 3
  • 13
  • possible duplicate of http://stackoverflow.com/questions/5643635/how-to-get-selected-html-text-with-javascript see if that helps you. – abc123 Jan 28 '13 at 22:29
  • my problem with IE this code does work with all the browsers but doesn't work with IE – Develop Smith Jan 28 '13 at 22:47

1 Answers1

0

DEMO: http://jsfiddle.net/ytJ35/

The below is taken from How to get selected html text with javascript?

this javascript function works in IE7 and above:

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}

Tested in chrome, IE10, IE6, IE7

Community
  • 1
  • 1
abc123
  • 17,855
  • 7
  • 52
  • 82