Ways to switch the positions of two characters in a text box

Is there a way to access the text content of a textarea and swap the two characters around the cursor using Javascript? I am interested in creating a Chrome extension that will allow me to quickly correct typos in Gmail. (I am assuming that the main editing area in Gmail is a textarea).

I understand this may seem like a simple question, but I have been unable to find a solution on my own. While I am not a seasoned programmer, I have successfully written code snippets in other scripting languages to accomplish similar tasks. Despite this, I am struggling with implementing it in Javascript specifically.

Answer №1

Check out the code snippet at http://jsfiddle.net/Lg3Ng/

HTML:

<textarea id="my_text" onclick="changeChar();"></textarea>

JAVASCRIPT:

function changeChar() {    
    var pos = getCaretPosition(document.getElementById("my_text"));
    //alert(pos);
    if (pos > 0) swapChars(pos - 1);
}

function swapChars(pos) {

    var cur_val = document.getElementById("my_text").value;

    var firstChar = cur_val.charAt(pos);
    var secondChar = cur_val.charAt(pos + 1);

    var startString = cur_val.substr(0, pos);
    var endString = cur_val.substring(pos + 2);

    document.getElementById("my_text").value = startString + secondChar + firstChar + endString;
}


// Courtesy of http://demo.vishalon.net/getset.htm
function getCaretPosition(ctrl) {

    var CaretPos = 0;
    // For IE 
    if (document.selection) {

        ctrl.focus();
        var Sel = document.selection.createRange();

        Sel.moveStart('character', -ctrl.value.length);

        CaretPos = Sel.text.length;
    }
    // For Firefox
    else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
        CaretPos = ctrl.selectionStart;
    }

    return (CaretPos);

}

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

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...

Attempting to add text one letter at a time

Hey there! I'm new to JavaScript and Jquery, and I need some help. My goal is to display text letter by letter when a button is clicked using the setTimeout function. However, I seem to be encountering some issues. Any assistance would be greatly appr ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...

Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array: Here is my query: router.get('/', function(req, res) { var userSubscribed = req.user.email; db.posts.find({ "SubscriberList": { $elemMatch: userSubscrib ...

Ways to showcase Switch/Case in two separate drop-down menus

I'm currently working on a PHP file with a switch/case structure that I believe is in JSON format. While I may not be an expert in PHP, AJAX, and JSON, I'm really putting effort to learn more about it. <?php switch($_GET['make'] ...

Can MUI FormControl and TextField automatically validate errors and block submission?

Are MUI components FormControl and TextField responsible for error handling, such as preventing a form from being submitted if a required TextField is empty? It appears that I may need to handle this functionality myself, but I would like some clarificatio ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

A simple way to deactivate a React component (or the onClick event itself) using the onClick event

I have come across similar inquiries, but unfortunately, none of the solutions provided seem to work in my particular scenario. I am hopeful that someone can shed some light on what might be causing the issue. In my ReactApp, there are 3 card components t ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

How can we redirect using an OnClick event handler in React.js?

I've been doing a lot of reading and trying to understand how to redirect using withRouter in React. However, I came across some information stating that when onClick occurs, the page should be redirected to a specific link. Additionally, I learned th ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

Modifying the href attribute of links within various occurrences of an element using jQuery based on its content

Here is an illustration of a recurring element on a webpage <td class=" market all"> <a href="linktosomesite?param=123" target="_blank">123</a> </td> Similar elements change the parameter, resulting in links like: <td clas ...

I am facing an issue with my middleware setup. It functions correctly when I include it in my app.js file, but for some reason, it does not work when I add it to my server.js file

Displayed below is my App.js information: const express = require("express"); const dotenv = require("dotenv"); const movieRouter = require("./routes/movieRoutes"); const userRouter = require("./routes/userRoutes"); ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

Variable Stores the Results of Node.js http.request

Hello everyone, I've been working on a project where I need to pass the results from an https.request in my node.js code to a variable. The https.request is set up to communicate with a SOAP API and receive the response successfully. My main objectiv ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...