Ryan Baker
Ryan Baker

Reputation: 39

Disable and re-enable user input without leaving textarea

I have been working on a small personal project that requires me to be able to enable and disable text input in a textarea through key commands. It will function similar to the way Vi/Vim handle insertion and command mode.

I cannot seem to figure out an elegant way to perform this task. Setting the textarea to disabled means that the user can no longer move their cursor caret through the text. Setting the keydown event to return false works for disabling the field, but obviously cannot re-enable it because it will instantly return false before reaching any other logic.

If there is any logic prior to the return false then the textarea takes the character input. I had attempted a version which accepts this input and instantly reverts it if it's not set to insertion mode, but this feels clunky and caused more problems than it was worth (plus it's not really instant...)

Upvotes: 0

Views: 338

Answers (3)

user1289347
user1289347

Reputation: 2407

I made a fiddle of this, just a simple demo, hitting d disables the field and hitting e enables it. Other characters can be entered while enabled. http://jsfiddle.net/gKDDh/1/

Try this, set a hidden field that contains the same text as the textarea. Now never actually disable the textarea, just maybe change the background color or text color so the user can differentiate between disabled and not. Then setup your logic like this.

onkeydown {
  if (state == disabled and hidden field value <> textarea value) {
    copy value from hidden field to textarea
  }
  else if (state == enabled) {
    copy value from textarea to hidden field
  }

basically what we are doing is keeping constant track of what the value should be, and only allowing a change when the state is enabled.

Upvotes: 1

marteljn
marteljn

Reputation: 6516

Using JQuery:

var txt = $("#txt");
txt.on("keyup",function(e){
  //Hit shift to disable
  if (e.keyCode === 16){
    $(this).attr("disabled","disabled");
  } 
}); 

$("body").on("keyup",function(e){
  //Hit enter to enable
  if (e.keyCode === 13){
    txt.removeAttr("disabled","");
  } 
});

Here is a demo:

http://jsfiddle.net/JMyTY/1/

Upvotes: 1

Pevara
Pevara

Reputation: 14310

I am not familiar with Vi/Vim but I think you are trying to achieve something like this: http://jsfiddle.net/FSjTa/

$('#text').keydown(function() {
    if ($(this).hasClass('command-mode')) {
        return false;            
    }
});
$('#btn-toggle').click(function() {
    $text = $('#text');
    if ($text.hasClass('input-mode')) {
        $text.removeClass('input-mode');
        $text.addClass('command-mode');
        $(this).html('command mode');
    } else {
        $text.removeClass('command-mode');
        $text.addClass('input-mode');
        $(this).html('input mode');
    }
});

I think the code should explain itself. If not, feel free to ask!

Upvotes: 1

Related Questions