Search code examples
javascriptjqueryuppercasegetselection

Upper case a selection of text in a textarea


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.


Solution

  • 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.