3

I have a dashboard at work and I want people to be able to change the text on the tabs in order to create categories which fit them best.

I wanted single line text which would disregard changes on Esc or commit the changes on Enter or Blur.

I found the answer but figured I would post in order to help others.

Anthony Graglia
  • 5,355
  • 5
  • 46
  • 75

1 Answers1

0

Here is the HTML markup:

<span contenteditable="false"></span>

Here is the jQuery/javascript:

$(document).ready(function() {
    $('[contenteditable]').dblclick(function() {
        $(this).attr('contenteditable', 'true');
        clearSelection();
        $(this).trigger('focus');
    });

    $('[contenteditable]').live('focus', function() {
        before = $(this).text();
        if($(this).attr('contenteditable') == "true") { $(this).css('border', '1px solid #ffd646'); }
    //}).live('blur paste', function() {
    }).live('blur', function() {
        $(this).attr('contenteditable', 'false');
        $(this).css('border', '1px solid #fafafa');
        $(this).text($(this).text().replace(/(\r\n|\n|\r)/gm,""));

        if (before != $(this).text()) { $(this).trigger('change'); }
    }).live('keyup', function(event) {
        // ESC=27, Enter=13
        if (event.which == 27) {
            $(this).text(before);
            $(this).trigger('blur');
        } else if (event.which == 13) {
            $(this).trigger('blur');
        }
    });

    $('[contenteditable]').live('change', function() {
        var $thisText = $(this).text();
        //Do something with the new value.
    });
});

function clearSelection() {
    if ( document.selection ) {
        document.selection.empty();
    } else if ( window.getSelection ) {
        window.getSelection().removeAllRanges();
    }
}

Hope this helps someone!!!

Anthony Graglia
  • 5,355
  • 5
  • 46
  • 75
  • This is not enough, because I can still copy and paste into this textbox, which totally confuses your code and shows newlines anyway. Furthermore, your code strips all HTML (by using only 'text') - so I'm in fact not quite sure why you don't just use a textbox. – Gijs Jun 28 '12 at 08:04
  • You can also use .html(). This is for text which is on a tab or something so you dont want it as a textbox. Only once they double-click, can you then edit it. As for 'paste', there is a commented line for that too. You can handle it as you please. – Anthony Graglia Jun 28 '12 at 09:42
  • you should update this to `.on()` because `.live()` no longer exists. – Ilan Biala Feb 03 '14 at 20:52
  • .live() exists but is now depreciated. At the time of the post, .live() was the way to go. If you are using jQuery 1.7+, you should use .on(). – Anthony Graglia Feb 03 '14 at 23:03