Search code examples
javascriptjquerytablesorterhtml-input

jQuery Tablesorter, Focus to select the content


I would like to select the content of a Tablesorter cell using JQuery.

For example I applied the method setSelectionRange in a input text. Good auto select text.

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />

I want same effect to the content of a Tablesorter cell (DIV)

<div class="" contenteditable="true">0,00</div>

How to ?


Solution

  • If you're not using the editable widget for my fork of tablesorter (demo)

    $('div[contenteditable]').on('focus', function() {
      var cell = this;
      // select all text in contenteditable
      // see http://stackoverflow.com/a/6150060/145346
      var range, selection;
      if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(cell);
        range.select();
      } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(cell);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    });
    

    If you are using the editable widget, then use the editable_selectAll option.


    Update: this method works as well (demo)

    That is, if your browser supports it - see caniuse & this demo.

    $('div[contenteditable]').on('focus', function() {
      setTimeout(function(){
        document.execCommand('selectAll', false, null);
      }, 1);
    });