javascript - highlight the content within a table cell and automatically populate the input field on the corresponding row

Currently, I am using the document.onmouseup event to select text. However, my code only allows me to specify one input. How can I modify it to select text from the first row and place it into the input in the first row, and do the same for the second row?

The following is the code snippet (source: On Text Highlight Event?):

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

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

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

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

Answer №1

After implementing the ShowSelection() function found here, I was able to achieve the desired functionality.

To enable this feature on specific inputs, simply assign a common class to those inputs and ensure that you attach the mouseup event to all of them. The solution provided below outlines the necessary steps:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now ...

Tips for submitting an AJAX form in grails without relying on a traditional submit button

I am utilizing a g:formRemote tag to submit a form via ajax. <g:formRemote name="listAll" update="menuItemAJAX" url="[controller: 'superWaiter', action:'menuItem']" onSuccess="additionalContent()"> <a h ...

Highcharts - problem with chart width being fully rendered

I am currently using a Highcharts column chart and I am looking to make it a fully responsive chart with 100% width. The container for the chart is a simple <div> without any additional formatting. Upon document load, the chart remains at a fixed wid ...

First, the image is reduced by width until it reaches its maximum width, then the height is adjusted proportion

I have an image with the dimensions of 1200 x 200px. In the center of this image, there is a space measuring 500 x 200px which represents the main content of the entire image. Flanking this main content are additional contents on each side. It is important ...

`Is it possible to place div elements on the left and right sides of another div element?`

Is there a way to format two div elements so that they are aligned to the left and right of another div element, similar to the example below? <div id="container"> <div id="left">Left.</div> <div id="box">This is a box.&l ...

A guide on detecting overflow in a React functional component

I am in search of a way to determine if a div contains overflowing text and display a "show more" link if it does. While researching, I came across an insightful Stack Overflow answer on checking for overflow in a div. The answer suggests implementing a fu ...

unable to bypass mongoose nested documents

I'm currently working with mongoose and node in an effort to paginate data from sub-documents. I've managed to limit the subdocuments, but skipping them seems to be a challenge. The specific versions I'm using are: Mongo 3.0.0 Node 0.10.3 ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Adding style to freshly generated content with class inclusion

Specifically speaking, when loading content from example.php, pay attention to the form with the class "aj-c-p" which is used for submitting user comments via Ajax (See code below). <form class="aj-c-p" action="set_comentario.php" method="post"> < ...

Obtain data from files within a React frontend application

I have integrated an API endpoint into my NodeJS application. The purpose of this endpoint is to locate a specific file in a folder based on the filename provided in the request. Here's how I am approaching this: const fileDirectory = 'C:/Sites/p ...

The ng-view directive appears to be missing in the AngularJS framework

I am attempting to create a route using AngularJS, but when I launch my application, the ng-view does not display anything. I am new to AngularJS. index : <!DOCTYPE html> <html lang="en"> <head> <title>CRUD</title> </ ...

ng-repeat does not update model when using track by

I've been facing an issue with checklist-model while working with an array of check-boxes. The problem arises when I try to delete selected items within an ng-repeat loop. Everything works fine initially, but when I add track by $index along with ng-r ...

Integrating jQuery Tooltip with Mouseover Event

I'm currently involved in creating a map of MIT projects for an architectural firm, and facing the challenge of maintaining the red dots mouseover state even when the mouse hovers over the tooltips that appear. Presently, the mouseover effect turns of ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...

Retrieving intricate JSON data from a specific web address

I need assistance in extracting and printing the date value from the JSON content available at the specified URL. Specifically, I am looking to retrieve the date value of "data.content.containers.container.locationDateTime" only if the "data.content.conta ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

Issue: 040A1079 - Failure in RSA Padding Check with PKCS1 OAEP MGF1 Decoding Error Detected on Amazon Web Services

Utilizing the crypto package, I execute the following tasks: Using crypto.generateKeyPairSync() to create publicKey and privateKey The keys are generated only once and stored in the .env file Applying crypto.publicEncrypt() to encrypt data before savin ...

Using Sequelize to update all values in a JSON file through an Express router.put operation

I've been working on a feature in my Express router that updates data in a MySQL schema for 'members' of clubs. The members table has various columns like member_id, forename, surname, address, etc. I've successfully created an Express ...

Updating the opacity of the alphaMap in THREE.JS R76 does not cause the desired change

I am working on a tunnel project that involves a rotating texture and alpha map. My goal is to adjust the opacity of the alpha map using tweening effects. Initially, I set the opacity to 0 and then try to increase it gradually. However, the live view does ...

Difficulty in detecting the collision between the character and the border in the game

My collision detection works perfectly except for when the character collides with the border. I want the character to respawn, so I implemented this code: left = 10; var reLeft = {'left':left + "px"}; $('#char').css(reLeft); top = ...