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>:practice caseThis 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
LVL 3
Pedro ChagasWebmasterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
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.
0
Pedro ChagasWebmasterAuthor Commented:
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
0
Ray PaseurCommented:
I removed this comment because the code sample was somewhat brittle (sometimes broken on multiple changes) and because Rob's solution was so much better.  Best to all, ~Ray
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

RobOwner (Aidellio)Commented:
This will wrap whatever you select with html <b> tags: http://jsbin.com/baviku/1/edit
html
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<textarea name="change" rows="4" cols="50" id='selecttext'>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>
</body>
</html>

Open in new window

javascript:
$(function() {
	$("#doit").click(function() {
		//change the selected text to something like:<b>selected text</b>

		var ta = $("#selecttext"); // your textarea has an id 'selecttext'
		
		var istart = ta[0].selectionStart;
		var iend = ta[0].selectionEnd;
		console.log('start: '+istart+' end: '+iend);
		var mytext = ta.val();
		console.log('mytext: '+mytext);
		var seltext = mytext.substr(istart,iend-istart);
		console.log('selected: ' + seltext);
		var newtext = '<b>' + seltext + '</b>';
		ta.val(mytext.replace(seltext,newtext));

	});

});

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
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.
0
Pedro ChagasWebmasterAuthor Commented:
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:1the second select:2the third select:3
For me work fine.

The best regards, JC
0
Ray PaseurCommented:
Illustration of the issue
0
Pedro ChagasWebmasterAuthor Commented:
Hi @Ray,
you're right, thanks for the advise.
I will open a new question to try fix that issue.

The best regards, JC
0
Pedro ChagasWebmasterAuthor Commented:
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
0
RobOwner (Aidellio)Commented:
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
0
RobOwner (Aidellio)Commented:
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

0
RobOwner (Aidellio)Commented:
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

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.