javascript - select text in table cell and autofill the input on the same row

一曲冷凌霜 提交于 2020-01-06 06:04:10

问题


Right now I'm using document.onmouseup event to select the text. But I'm only able to specify one input in my code. How do I select the text in the first row and put it in the input in the first row, and do the same thing for the second row?

The code snippet is here (from On Text Highlight Event?):

var t = '';
function gText(e) {
t = (document.all) ? document.selection.createRange().text : document.getSelection();

document.getElementById('input1').value = t;
}

document.onmouseup = gText;
if (!document.all) document.captureEvents(Event.MOUSEUP);

https://jsfiddle.net/nrdq71pz/1/


回答1:


I have used ShowSelection() function from here.

You can add a common class to the inputs where you want this feature. Also, you have to attach mouseup event to all the inputs. Please see below solution.

var els = document.getElementsByClassName('selection');
function getSelection(textComponent) {
  var selectedText;
  if (textComponent.selectionStart !== undefined) { // Standards Compliant Version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  } else if (document.selection !== undefined) { // IE Version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  return selectedText;
}

for (var i = 0; i < els.length; i++) {
  els[i].addEventListener('mouseup', function() {
    this.value = getSelection(this);
  })
}
<table>
  <tr>
    <td>Test code 1</td>
    <td>
      <input type='text' id='input1' class="selection" />
    </td>
  </tr>
  <tr>
    <td>Test code 2</td>
    <td>
      <input type='text' id='input2' class="selection" />
    </td>
  </tr>
</table>


来源:https://stackoverflow.com/questions/47786704/javascript-select-text-in-table-cell-and-autofill-the-input-on-the-same-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!