[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Javascript or Jquery - Change selected text

Posted on 2014-08-05
12
Medium Priority
?
1,481 Views
Last Modified: 2014-08-06
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
0
Comment
Question by:Pedro Chagas
  • 4
  • 4
  • 4
12 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40242067
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
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 40242135
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
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 40242361
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 43

Accepted Solution

by:
Rob earned 1800 total points
ID: 40243007
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40243905
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
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 40244041
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40244727
Illustration of the issue
0
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 40244892
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
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 40245107
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
 
LVL 43

Expert Comment

by:Rob
ID: 40245110
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
 
LVL 43

Expert Comment

by:Rob
ID: 40245119
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
 
LVL 43

Expert Comment

by:Rob
ID: 40245172
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month18 days, 16 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question