On my text area with codemirror I am trying to be able to select/ highlight text and then be able to click on my bold button and should wrap the bold tags around it.
I have looked at
SO Question 1 , SO Question 2
But does not seem to work with code mirror.
My Question is: With codemirror How could I grab the selected text and then make sure when I click on the bold button it wraps the text correctly?
Codepen Code View
Codepen Full View
Script
var editor = document.getElementById('text-editor');
var string = grabed_text();
$("#text-editor").each(function (i) {
editor = CodeMirror.fromTextArea(this, {
lineNumbers: true,
mode: 'html'
});
$('button').click(function(){
var val = $(this).data('val');
switch(val){
case 'bold': editor.replaceSelection('<b>' + string + '</b>');
break;
}
});
});
function grabed_text() {
}
HTML
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default" onLoad="text_editor();">
<div class="panel-heading">
<button type="button" data-val="bold" class="btn btn-default">Bold</button>
</div>
<div class="panel-body">
<textarea id="text-editor" name="text-editor" class="form-control"></textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="question-iframe"></div>
</div>
</div>
</div>
Issue in your code is in the switch case where you're handling bold button.
case 'bold':
editor.replaceSelection('<b>' + string + '</b>');
break;
Here you're replacing the current selection by wrapping <b>
tags around string
variable but it's not defined anywhere. Ideally it should reflect the current selection from your editor. So I suggest you change your code like below.
// inside your click handler
var val = $(this).data('val');
var string = editor.getSelection();
switch(val){
case 'bold': {
editor.replaceSelection('<b>' + string + '</b>');
break;
}
}
Here's a Pen with the above changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With