Reputation: 105
I trying todo a simple BB code for my textarea. My code works fine, but it not takes selected text. Example: TEXT. If i select with mouse on TEXT ant choose the [B] tag it does not update text to: [b]TEXT[/b]. It writes after TEXT. Example: TEXT[b][/b]. Any suggest?
<script type="text/javascript">
function formatText(tag) {
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value += '' + tag + '';
}
</script>
<a href="#" class="btn hint--bottom" aria-label="Bold Text" onclick="formatText ('[b][/b]');"><i class="fas fa-bold"></i></a>
Upvotes: 0
Views: 82
Reputation: 4592
first split the tag so that we get [b] and [/b] the rest of your code is good.
tested here https://jsfiddle.net/x0tfyna9/12/ on chrome
<body>
<textarea id="text"></textarea>
<a href="#" onclick="formatText('[b][/b]');"><i class="fas fa-bold">xasada</i></a>
<script>
function formatText(tag) {
var tags = tag.split("]", 2).map(function(t) {
return t + "]";
});
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + tags[0] + selected_txt + tags[1] + after_txt;
}
</script>
</body>
Upvotes: 1
Reputation: 582
You were just adding your tag at the end but you want the tag to wrap the selected text. then, You can do it like this. Also, edited the HTML code accordingly.
function formatText(tag) {
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt+'['+tag+']' +selected_txt +'[/' +tag+']' + after_txt;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<a href="#" class="btn hint--bottom" aria-label="Bold Text" onclick="formatText ('b');"><i class="fas fa-bold">Click</i></a>
<textarea id="text">I trying todo a simple BB code for my textarea. My code works fine, but it not takes selected text. Example: TEXT. If i select with mouse on TEXT ant choose the [B] tag it does not update text to: [b]TEXT[/b]. It writes after TEXT. Example: TEXT[b][/b]. Any suggest?</textarea>
</body>
</html>
Upvotes: 1