0

I'm getting an undefined is not a function error when I try and run the following code:

$(document).ready(function() {
    $("#textarea").select(function() {
        var selection = window.getSelection();
        $("#upper").click(function() {
            // alert(selection);
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        });
    }); 
});

I'm trying to select text from a textarea, and click a button to make the selection uppercase. Here is a JSFiddle of the complete code.

mpdc
  • 3,550
  • 5
  • 25
  • 48

1 Answers1

4

getSelection returns an object. You need to call toString() on it.

$(document).ready(function () {
    var selection;
    $("#textarea").select(function () {
        selection = window.getSelection().toString();
    });
    $("#upper").click(function () {
        if (selection) {
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        }
    });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/8syb2d8j/4/

Notes:

  • your event handlers were nested (usually a bad idea)
  • I added a check to ensure that there is a selection before trying to upppercase it.
  • as, potentially, the text you highlight may occur more than one, using replace is actually not a great solution. Try highlight the second i and see what I mean. You should use the properties of the selection object instead to work out the exact part of the string that was selected,

After browsing around for portable solutions, I found the jQuery TextRange plugin, which, based on the demo is more than enough for this problem.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Thanks. The nesting was because I thought my error had something to do with variable scope! – mpdc Mar 30 '15 at 15:28
  • @mpdc: Nah, just move the variable back a level. Please note the problem I have noted at the end. You may want to rethink how you do this. :) – iCollect.it Ltd Mar 30 '15 at 15:29
  • I'm looking at the second answer here for inspiration: http://stackoverflow.com/questions/17836488/jquery-surround-highlighted-text-with-span :) Thanks. – mpdc Mar 30 '15 at 15:30
  • That is a good example. Use the `range` properties provided by `getSelection()` – iCollect.it Ltd Mar 30 '15 at 15:31
  • Just been browsing around the options for doing it "properly" (i.e. using selection ranges) and there is a lot *noise* out there. Browser compatibility *will* be an issue. – iCollect.it Ltd Mar 30 '15 at 15:42