I have just figured out how to use javascript to select text thanks to the Anvil Community (Select text trigger). But how can I apply it to one text area and not the all components?
I changed mouseup to the selectionchange event so that mouse, touch, and keyboard selection all work (was originally working on my phone to realize nothing was getting through). With selectionchange, it needs to be set at the document level for reasons I won’t pretend to understand. Because of that, I then compare the active element to the text_area_1’s dom_node to restrict it to that (so put all your code under that if block )
from ._anvil_designer import Form1Template
from anvil import *
from anvil.js import get_dom_node, document
class Form1(Form1Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
# Store the DOM node of text_area_1 for comparison in the event listener
self.text_area_1_node = get_dom_node(self.text_area_1)
# Add event listener for selectionchange event
document.addEventListener('selectionchange', self.selectionchange_listener)
def selectionchange_listener(self, event):
if document.activeElement == self.text_area_1_node:
selected_text = self.text_area_1.text[self.text_area_1_node.selectionStart:self.text_area_1_node.selectionEnd]
print("Selection: " + selected_text)
1 Like
This works neatly. Thank you so much!
1 Like