javascripthtml-tablegetselection

getSelection not working properly in Chrome


In the below code selectTextOnly() gets called by clicking on any of the cells or the div at the top via onclick.

In Chrome Everything works if I click on any of the table cells. However, when I click on the div, the function gets called but no selection gets set.

Clicking both the div and the cells works as expected in Firefox.

Why does clicking the div not select the cells in Chrome?

Example on jsFiddle

Html:


<div style="width: 45px; height:20px; background-color:#339900" onclick="selectTextOnly('notes')" id="test"></div>

<table id="all" class="optionEmail"  width="100%" border="0">
  <tr>
    <td id="notes" onclick="selectTextOnly('notes')">This is the notes cell</td>
  </tr>
  <td> 
  <table id="email">
  <tr>
    <td onclick="selectTextOnly('email')">This is the email cell</td>
  </tr>
  <tr>
    <td id="itinerary" onclick="selectTextOnly('itinerary')">This is the flights cell</td>
  </tr>
  <tr>
    <td onclick="selectTextOnly('all')">This is the all cell</td>
  </tr>
  </table>
  </td>
</table>

javascript:


function selectTextOnly(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
    }
}

Solution

  • Try change you code into this:

    function selectTextOnly(containerid) {
        var text = document.getElementById(containerid);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        } 
    }
    

    The if stament is used to check document.body.createTextRange used only for IE; the else for all other browsers.

    Demo: http://jsfiddle.net/IrvinDominin/2K3ZT/2/