Link to home
Start Free TrialLog in
Avatar of Pedro Chagas
Pedro ChagasFlag for Portugal

asked on

Javascript or Jquery - Change selected text

Hi E's,
I need a solution for change selected text inside a <textarea>.
In practice I want to select some text in <textarea>, and change the select text to, like: <b>selected text</b>:User generated imageThis is the code for show what we see in attach image:
<html>
<head>
</head>
<body>
<textarea name="change" rows="4" cols="50">This is the text that can be selected. Words can be selected as a set of words.</textarea>
<a name="doit" id="doit" href="#">do it</a>
<script>
$("#doit").click(function() {
    //change the selected text to something like:<b>selected text</b>
});
</script>
</body>
</html>

Open in new window

Is possible do this in js ot jquery and how?

The best regards, JC
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

It's possible, but most textarea fields that need editing controls choose TinyMCE or CKEditor since they have rather intuitive interfaces.  I would not try to reinvent this particular wheel -- just download one of the editors and give it a try.  WordPress (millions of successful sites) uses TinyMCE.
Avatar of Pedro Chagas

ASKER

Hi @Ray, I known that wheels. I have some sites with that wheels, in particular CKeditor.
The reason why I ask, is because, in some particular part of a project, I need to change normal text to bold text, only, I not will need the other tools, just bold tool.
Other reason is, I don't want to install more library's in the project, just for use one tool (bold).
My idea is select text, and transform that text to other thing.
Is possible help me, and forget the wheels? I assume the responsibility!

~JC
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For anyone coming to this in the future, be aware that the accepted solution will only bold the first instance of the selected text.  This happens no matter where in the text the selection is made.  And a duplicate selection, further down in the textarea, will not be located; the bold action will be applied repeatedly to the first instance that matches the selection.  I think this line is the culprit:

ta.val(mytext.replace(seltext,newtext));

Not sure exactly how to remediate that, but it's worth being aware.
Hi @Ray,
<<be aware that the accepted solution will only bold the first instance of the selected text>>.
I test the solution, and will bold all the instances. I do the test and I attach the images:
The first select:User generated imagethe second select:User generated imagethe third select:User generated image
For me work fine.

The best regards, JC
Hi @Ray,
you're right, thanks for the advise.
I will open a new question to try fix that issue.

The best regards, JC
This is the correct code:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <title>Alterar texto seleccionado</title>
</head>
<body>
<textarea name="change" id="selecttext" rows="4" cols="50">This is the text that can be selected. Words can be selected as a set of words.</textarea>
<a name="doit" id="doit" href="#">do it</a>

    <script>
        $("#doit").click(function() {
            var textarea = document.getElementById("selecttext");
            if ('selectionStart' in textarea) {
                    // check whether some text is selected in the textarea
                if (textarea.selectionStart != textarea.selectionEnd) {
                    var newText = textarea.value.substring (0, textarea.selectionStart) + 
                        "<b>" + textarea.value.substring  (textarea.selectionStart, textarea.selectionEnd) + "</b>" +
                        textarea.value.substring (textarea.selectionEnd);
                    textarea.value = newText;
                }
            }
            else {  // Internet Explorer before version 9
                    // create a range from the current selection
                var textRange = document.selection.createRange ();
                    // check whether the selection is within the textarea
                var rangeParent = textRange.parentElement ();
                if (rangeParent === textarea) {
                    textRange.text = "<b>" + textRange.text + "</b>";
                }
            }
        });
    </script>
</body>
</html>

Open in new window

Thank you @Ray for detected the issue.

The best regards, JC
It's a simple matter of using a regex in the replace but it goes against the logic of replacing what you're highlighting.

Take an example with a post here at EE. I only want to wrap the selected text in the selected tag, not everything else that matches the selected text.

So it depends on your application and why you're replacing the text
To replace all occurances it's a simple matter of adding one line but you'd want to be sure you want to replace all occurances, I'm not sure I agree you would:

var re = new RegExp(seltext,"g"); // replace all occurances e.g. "g" is global
ta.val(mytext.replace(re,newtext));

Open in new window

The code I've posted above, as pointed out, will replace the *first* occurrence of the string and not necessarily the selected text.

To circumvent that issue, all that needs to be done is to break the string into two from the beginning of the text to where the selected text begins, and the second part is the rest of the string.  Then replacing the first occurrence is replacing the correct selected text.  Kudos to all who pointed this out.

<script>
$(function() {
	$("#doit").click(function() {
		var ta = $("#selecttext"); // your textarea has an id 'selecttext'
		var istart = ta[0].selectionStart;
		var iend = ta[0].selectionEnd;
		character_count=iend-istart
		firstpart = ta.val().substr(0,istart)
		remainder = ta.val().substr(istart)
		var newtext =firstpart+ '<b>' + remainder.substr(0,character_count) + '</b>' + remainder.substr(character_count);
		ta.val(newtext);
	});
});
</script>

Open in new window