Reputation: 143
I want to make my own html text editor very simple code. And When I click Bold button, in textarea, must be insert [B]boldtext[/B] and "boldtext" can be select like this photo.
I wrote tihs code,
function TextEditor(startSyntax,endSyntax,elementID)
{
var textarea = $('#' + elementID)
var start = textarea[0].selectionStart;
var end = textarea[0].selectionEnd;
var text = textarea.val();
if (start == end) {
return text.substring(0,start) + startSyntax + "text" + endSyntax + text.substring(end,text.lenght);
};
return text.substring(0,start) + startSyntax + text.substring(start, end) + endSyntax + text.substring(end,text.lenght);
}
$("#btnKaydet").on("click", function() {
$("#txtMesaj").val(TextEditor("[B]","[/B]","txtMesaj"));
});
What I wrote inserts text but it does not select "boldtext" text after adding the tags, like in photo. How can I do this with jquery? Thanks
Upvotes: 0
Views: 527
Reputation: 1804
You will have to write a function to select the text that was previously selected. Since you're changing the entire text in the textarea, it won't remember what was selected previously. Here's a link with an example function on how to do this.
http://programanddesign.com/js/jquery-select-text-range/
Code for the solution:
function TextEditor(startSyntax,endSyntax,elementID)
{
var textarea = $('#' + elementID)
var start = textarea[0].selectionStart;
var end = textarea[0].selectionEnd;
var text = textarea.val();
if (start == end) {
textarea.val(text.substring(0,start) + startSyntax + "text" + endSyntax + text.substring(end,text.lenght));
}
else
{
textarea.val(text.substring(0,start) + startSyntax + text.substring(start, end) + endSyntax + text.substring(end,text.lenght));
}
selectText(textarea[0], start+3, end + 3);
}
$("#btnKaydet").on("click", function() {
TextEditor("[B]","[/B]","txtMesaj")
});
function selectText(input, start, end)
{
if(input.setSelectionRange) {
input.focus();
input.setSelectionRange(start, end);
} else if(input.createTextRange) {
var range = input.createTextRange();
input.collapse(true);
input.moveEnd('character', end);
input.moveStart('character', start);
input.select();
}
}
jsfiddle: http://jsfiddle.net/wPLBy/12/
NOTE: I only tested this on chrome, it may behave differently in different browsers.
Upvotes: 2