4

how to replace selected text in html textarea?

mardagz to [b]mardagz[\b]

here's my code but won't work..

function getSelectedText(){ 
if(window.getSelection){ 
    return window.getSelection().toString(); 
} 
else if(document.getSelection){ 
    return document.getSelection(); 
} 
else if(document.selection){ 

    return document.selection.createRange().text; 
}} 



function bbrep(start, end){
 $("#pPost").val($("#pPost").val().replace(getSelectedText(), start + getSelectedText() + end))};

key

$("#bbbold").click(function(){
          bbrep("[b]", "[/b]");
          return false;      
 })

anyone has an idea for this? :)

Pseudorandom
  • 716
  • 3
  • 14
  • 30

5 Answers5

13

Here a complete tested & working example

function getSelectedText() {
    var len =$("#pPost").val().length;
    var start = $("#pPost")[0].selectionStart;
    var end = $("#pPost")[0].selectionEnd;
    var sel = $("#pPost").val().substring(start, end);
    return sel;
}


function bbrep(start, end){
var tmpVal = getSelectedText();
$("#pPost").val($("#pPost").val().replace(tmpVal, start + tmpVal + end));

}

$("#bbbold").click(function(){
      bbrep("[b]", "[/b]");
      return false;      

})

here is the html code snipet

<textarea rows="2" cols="20" id="pPost">mardagz
</textarea>
<input type="button" id="bbbold" value="clcikMe" />

here is a jsfiddle example i just did "it works"


Another jsfiddle that takes the index into account too, jsfiddle.net/SU7wd/58 <- works on that second a too

Daniel
  • 36,833
  • 10
  • 119
  • 200
  • 2
    It should be noted that this will always replace the FIRST occurrence of the selected text, not necessarily the selected text. IE: try replacing the second 'a' in mardagz or one of the many 'a's in abracadbra... – Chris Kerekes Apr 24 '14 at 20:00
  • @ChrisKerekes, for that all you have to do is a better replace , one that will take the index into account, take a look http://jsfiddle.net/SU7wd/58/ <- works on that second a too – Daniel Apr 24 '14 at 20:41
3

Just in case someone comes here later, I'll share my solution I found after some research, based on what's said above. I was looking for a solution that would replace what I ask to replace (and not the same substrings somewhere in the textarea), and also to leave with the focus at the end of the inserted text.

Here's the solution I came to:

function text_with_insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}    

function surround_sel_text( str_start, str_end ) {
  var el = $("#pPost");
  var focus_idx = el[0].selectionEnd + str_start.length + str_end.length;

  var text_with_end_insert = text_with_insert( el.val(), el[0].selectionEnd, str_end );
  el.val( text_with_insert( text_with_end_insert, el[0].selectionStart, str_start ) );
  el[0].selectionStart = focus_idx;
  el[0].selectionEnd = focus_idx;
}

$("#bbbold").on('mousedown' ,function() {
      surround_sel_text( '[b]', '[/b]' );
      event.preventDefault();     
});
BobMorley
  • 36
  • 5
Olga Farber
  • 306
  • 2
  • 7
2

This works:

function bbrep(start, end) {
    var str = $("#pPost").val();
    var word = "bar";//getSelectedText();
    var re = new RegExp("(\\b" + word + "\\b)", "ig");
    $("#pPost").val(str.replace(re, start + "$1" + end));
};

However I had to hard-code a string because your getSelectedText() method does not return anything.

Edit:

Instead of using .click, use .mousedown

By the time .click happens, the text is no longer selected.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • anyway iv'e added this one `$(this).live('mouseup', function() { selection = getSelectedText(); }); ` there's a result but `[b][/b]mardagz` instead of `[b]mardagz[/b]` – Pseudorandom Dec 06 '11 at 19:13
  • Again... use `mousedown` not `mouseup` or `click` you have to catch it before the selection goes away. – Kevin B Dec 06 '11 at 19:20
  • owhhh i got it bro :) hihi, i just generating new function :) hihi, thanks a lot anyway.. :) – Pseudorandom Dec 06 '11 at 19:30
1

Ok I had to rebuild this to work with my asp.net control. Think it about as simple as it will get. This one will replace what selected, and not the first word found like in the others.

Just make sure you give it the ID of your textbox.

You can call the function like this makeBBCode("[b]", "[/b]") . I Used OnClientClick on a asp image button to call it. [Ex: OnClientClick='makeBBCode("[b]", "[/b]")']

    String.prototype.insertAt = function (index, string) {
        return this.substr(0, index) + string + this.substr(index);
    }

    function makeBBCode(start, end) {
        var txtBox = document.getElementById("Object_Id_Here")
        txtBox.value = txtBox.value.insertAt(txtBox.selectionEnd, end).insertAt(txtBox.selectionStart, start);
    }
LastEnd
  • 71
  • 3
0

You can use:

https://github.com/timdown/rangyinputs

And simply call: replaceSelectedText

Nathan B
  • 1,625
  • 1
  • 17
  • 15