samedi 9 janvier 2016

How to undo selected / highlighted text when click on button with codemirror

Vote count: 0

I have a simple codemirror text editor I am working on with bootstrap. I can click on my bold and code buttons OK and it wraps the selected / highlighted text corrctly.

Question: When text is wrapped in a tag lets say <b>something</b> If I go and select / highlight it again and click same bold button how can I undo it in codemirror?

Here's a CodePen example

Script

<script type="text/javascript">
$(document).ready(function() {
    var editor = document.getElementById('text-editor');

    $("#text-editor").each(function (i) {

        editor = CodeMirror.fromTextArea(this, {
            lineNumbers: true,
            mode: 'html',

        });

        editor.on("change", function() {
            document.getElementById('question-preview').innerHTML=editor.getValue();
        });


        $('button').click(function(){

            var val = $(this).data('val');
            var string = editor.getSelection();

            switch(val){

                case 'bold': 
                    editor.replaceSelection('<b>' + string + '</b>');
                break;

                case 'code': 
                    editor.replaceSelection('<pre>' + string + '</pre>');
                break;
            }
        });
    });
});

</script>

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>
                    <button type="button" data-val="code" class="btn btn-default ">Code</button>
                </div>

                <div class="panel-body">
                    <textarea id="text-editor" name="text-editor" class="form-control"></textarea>
                </div>

            </div><!-- . / panel -->

        </div><!-- . / col -->

    </div><!-- . / row -->

    <div class="row">

        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div id="question-preview"></div>
        </div>

    </div><!-- . / row -->

</div>  

asked 1 min ago

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.



How to undo selected / highlighted text when click on button with codemirror

Aucun commentaire:

Enregistrer un commentaire