0

I'm trying to do something like.. When pressing CTRL+b it should add [b] and [/b] around the selected text. I can get the selected text by using this Javascript code: Get the Highlighted/Selected text

However... When I try something like this:

$(document).ready(function (){
    $('#message').on('keydown',function(e) {
        key = e.which;
        if(e.which == 39){
            str = getSelectionText();
            $("#message").replace(str,"[b]"+str+"[/b]");
        }
    })
});

it won't work. It will say "Object [object Object] has no method 'replace'" which is odd, because when I do alert(str); it will display the selected text.

Can anyone tell my why? Key 39 is right arrow key.

Thanks in advance

Community
  • 1
  • 1
MortenMoulder
  • 6,138
  • 11
  • 60
  • 116

1 Answers1

2

It's a jQuery object, that's why .replace wont work. You need to add .val() to get the actual value, then you have to set it as well:

var value = $("#message").val();
value = value.replace(str,"[b]"+str+"[/b]");
$("#message").val(value);
tymeJV
  • 103,943
  • 14
  • 161
  • 157