Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

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

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...