Search code examples
jquerytextareakeypressvarrevert

Default to original textarea val on Esc


I'm trying to make an textarea default to the original value upon hitting esc. I can't seem to pass the origVal from the main code into the keypress if/else.

Am I overthinking this or underthinking it?

Fiddle: https://jsfiddle.net/kirkbross/brkbcr5c/1/

$(function() {
    var origVal = $("#textarea").val(); // set original value of textarea    
    $('#textarea').keydown(function(e, origVal) {
        var code = e.keyCode || e.which;
        if (code == 13) {
            e.preventDefault();
            //submit code
        } else if (code == 27) {
            $(this).blur();
            $(this).val(origVal); // default to original value on Esc
        }
    });
});

Solution

  • You are almost there, the this in var origVal = $(this).val() points to the document element.

    Use a specific textarea selector.

    var origVal = $('#textarea').val()
    

    Updated Fiddle

    Also, remove origVal from keydown(function(e, origVal). The global origVal is accessible in keydown.