Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace my selected text in jQuery?

Tags:

jquery

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? :)

like image 694
Pseudorandom Avatar asked Oct 11 '25 12:10

Pseudorandom


2 Answers

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

like image 186
Daniel Avatar answered Oct 14 '25 04:10

Daniel


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();     
});
like image 28
Olga Farber Avatar answered Oct 14 '25 05:10

Olga Farber