How to switch on and off the readonly mode on runtime with a checkbox button for tinymce?

1.6k Views Asked by At

I have tinymce set to be ready only on initialization, but how can I set it to editable mode on runtime with a checkbox button?

html,

<textarea id="my_textarea_id" readonly="readonly">Some content here.</textarea>
<input type="checkbox" class="switch" /> <span>Turn editor on/ off</span>

js,

var readonly = $("textarea#my_textarea_id").attr("readonly") ? 1 : 0;

tinyMCE.init({
        theme : "advanced",
        mode: 'none',
        readonly : readonly,
        ...
});

var object = $('.switch');
object.click(function(){
            if(object.prop('checked') === true){ 
                $("#my_textarea_id").data('readonly','true');
            } else {
                $("#my_textarea_id").data('readonly','false');
            }
});
3

There are 3 best solutions below

0
On

try this:

var object = $('.switch');
object.change(function(){
            if(object.prop('checked') === true){ 
                $("#my_textarea_id").attr('readonly',true);
            } else {
                $("#my_textarea_id").attr('readonly',false);
            }
});
0
On

try this

var object = $('.switch');
object.change(function(){
     $('#my_textarea_id').attr('readonly',!this.checked);
})
0
On

If you are using a version of TinyMCE > 4.3.0, the following code should work:

var object = $('.switch');
object.click(function(){
    if(object.prop('checked') === true){
        tinymce.activeEditor.setMode('readonly')
    } else {
        tinymce.activeEditor.setMode('design')
    }
});

Reference: https://github.com/tinymce/tinymce/issues/2580