I am trying to set the text direction to RTL for the window.getSelection value. However, I'm having trouble figuring out how to remove getSelection from the current value

var userInput = document.getElementById('inputText').value;
 
            function insertAtCursor() 
            {
                if (window.getSelection)
                {
                    selectedText = window.getSelection();
                    document.getElementById('inputText').value = userInput + selectedText // modification required to remove the selected text from userInput

                }
            }
<textarea id="inputText">This is some sample text.</textarea><button onclick="insertAtCursor();">Insert Selected Text</button>

Answer №1

It is possible to extract the selected text and its position within the content using JavaScript. While there are no direct solutions for obtaining the text position from a <textarea>, an insightful post on Stack Overflow offers a method to retrieve this information from a <div>. Additionally, you can create a <div> that mimics the appearance of a <textarea>, as demonstrated in another Stack Overflow answer here. By merging these two approaches with some adjustments, it becomes feasible to manipulate text efficiently by utilizing the 'changeValue' function.

<html>
<style>
#main {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 28px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}
</style>

<body>
<div id="main" contenteditable>Samudrala RamuSamu</div>
<input type="button" onclick="changeValue()" unselectable="on" value="Get selection">
</body>

<script>
function getSelectionCharOffsetsWithin(element) {
    var start = 0, end = 0;
    var sel, range, priorRange;
    if (typeof window.getSelection != "undefined") {
        range = window.getSelection().getRangeAt(0);
        priorRange = range.cloneRange();
        priorRange.selectNodeContents(element);
        priorRange.setEnd(range.startContainer, range.startOffset);
        start = priorRange.toString().length;
        end = start + range.toString().length;
    } else if (typeof document.selection != "undefined" &&
            (sel = document.selection).type != "Control") {
        range = sel.createRange();
        priorRange = document.body.createTextRange();
        priorRange.moveToElementText(element);
        priorRange.setEndPoint("EndToStart", range);
        start = priorRange.text.length;
        end = start + range.text.length;
    }
    return {
        start: start,
        end: end,
        value: range.toString()
    };
}

function changeValue() {
    var mainDiv = document.getElementById("main");
    var sel = getSelectionCharOffsetsWithin(mainDiv);

    var mainValue = mainDiv.textContent;
    var newValue = mainValue.slice(0,sel.start) + mainValue.slice(sel.end) + sel.value;
    mainDiv.textContent = newValue;
}
</script>

</html>

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

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

Effortlessly implement CSS styling in a scoped shadow element with Vue3

I am facing an issue with applying styles to an anchor element in my code. Below is a snippet of the code: <template> <custom-button> #shadow-root (open) <a href="#"></a> <other-custom></other-c ...

Store data collected from a form within a Bootstrap modal into a PHP session variable

My goal is to utilize Bootstrap's modal component to collect user information and save it into a session. The form within the modal is designed for users to input their first name, last name, and email address. Upon clicking submit, this information ...

How can I use jQuery to set the color of every other row in a

I'm facing an issue where I want to use jQuery to set the color of alternate rows in an HTML table. However, every time I add a new row, the color of the entire table switches. Below is the JavaScript code snippet that I am utilizing: var alternate = ...

Unable to link href attribute in project

My issue is that clicking the updates button does not load its page. Here's the relevant part of the code: <div class="st-container"> <input type="radio" name="radio-set" checked="checked" id="st-control-1"/> <a href="home.html ...

Locate data objects using JavaScript keys

My object looks like this: { sunday: {status: "open", opening_time: "11:30 am", closing_time: "12:00 pm"}, monday: {status: "close", opening_time: "", closing_time: ""}, tuesday: {status: "close", opening_time: "", closing_time: ""}, wednesday: {st ...

Exploring the Functionality of Bootstrap 5 Collapse Component with VueJS 2

I am attempting to implement the Bootstrap 5 "collapse" component on a button in my VueJS2 project, but I am uncertain about how to integrate it. Within my single file component, the structure is as follows: <template> section: ...

Learn the method for showing and hiding a div element in AngularJS

There is a loader on my screen that stays visible until the page finishes loading or encounters an error. Within a div, I have the loader... <div id:loader class="loading"> ...and I want to toggle its visibility based on the page loading status. ...

My email address is not receiving emails from the PHP mail function

After extensive research, I am still unable to figure out why this email form is not sending messages to my address. Below is the HTML form code: <form id="contactMe" name="contact" method="post" novalidate="novalidate"> <fieldset> ...

Words program with the header feature incorporated

Hello, I am currently working with Laravel to build an HTML page and have successfully converted it to MS Word. However, I am now trying to add a header inside. Can anyone help me achieve this? Here is a snippet of my code: <body> <a class= ...

Refresh and storing canvas after submitting form

Before submitting a form, I am executing the following code. The process involves changing an image and then redrawing a canvas before saving it. Unfortunately, the issue is that the saved image does not reflect the changes made (it still shows the previ ...

Having trouble importing the named export `{module}` from a non-ECMAScript module with TipTap and Nuxt?

I'm using TipTap with Nuxt and running into some issues that I can't seem to resolve. Despite following suggestions from the repository's issues, I keep encountering these specific errors: ERROR in /Volumes/Projects/nuxt/candy-hub-lerna/no ...

When the browser width decreases, the layout's rows become wider

Here is the code snippet I'm using: <style> a.item { border:1px solid #aaa; background:#ddd; padding:10px; ...

Four columns positioned next to each other (Navigation Bar)

I've been trying to get these divs to display side by side for a menu bar, but they keep stacking on top of each other. I've experimented with margin-right/left/top/bottom, padding, and more, but nothing seems to work. Any suggestions? <div i ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

The attribute value in an input field is not effective in Angular

My routine usage involves employing an input tag and attempting to include text using the value attribute, but it seems to be malfunctioning. Here's the line of code in question: <input class="form-control input-sm" value="14" type="number" ng-mod ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

The Ajax login validation is not displaying

Currently, I am utilizing Laravel 4 to implement login validation through the use of AJAX. Below is the JavaScript validation code that I have: jQuery('#form-signin').submit(function() { var url = $(this).attr("action"); jQuery.ajax({ ...