display a two-character output when a single key is pressed during the keypressup event

While using the Google virtual keyboard and setting it on a textarea, I noticed an issue. When I type something in the textarea, two characters are printed - one uppercase and one lowercase.

To address this problem, I wrote a JavaScript function for the textarea. This function automatically capitalizes the letters after a dot "." is typed.

Now, I am trying to figure out how to remove one character so that only one character is printed in the textarea. Currently, every time I press a single key, two characters are printed. I have set up a keypress event on the textarea to handle this function.

function caps(e, textarea, value){
    var unicode = e.keyCode ? e.keyCode : e.charCode;
    var str = value.trim();
    str = str.charAt(str.length - 1);

    if((str == "." || value.length == 0) && (unicode >= 97 && unicode <= 122)){
        textarea.value = textarea.value + String.fromCharCode(unicode).toUpperCase();
        return false;
    }
    return true;
}

Answer №1

If you want to prevent the default behavior of an event, you can achieve this by using e.preventDefault();. Here is an example:

function capitalizeLetter(e, textarea, value){
    var unicode = e.keyCode ? e.keyCode : e.charCode; // handling ASCII codes

    var str = value.trim();
    str = str.charAt(str.length-1);
    if(str == "." || value.length == 0){
        textarea.value = textarea.value + String.fromCharCode(unicode).toUpperCase();
        e.preventDefault();
    }
}

input.addEventListener("keypress", function(e){
    if(e.keyCode == 8) return true;
    capitalizeLetter(e, input, input.value);

}, false)

Instead of using return false, you can modify the code like this:

input.onkeypress = function(){
    if(e.keyCode == 8) return true;
    return capitalizeLetter(e, input, input.value); // passing false as well from capitalizeLetter
}

Check out the Demo for a better understanding.

Answer №2

It appears that the solution lies in simply removing the last character before adding a new one. Here is a possible implementation, although it has not been tested thoroughly.

if((str=="." || value.length==0) && (unicode>=97 && unicode<=122)){
    /*Remove the previous character before adding a new one*/
    textarea.value = textarea.value.substring(0, textarea.value.length - 1);
    textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
    return false;
}

Depending on how this function is triggered, you might be able to prevent the character from being printed initially.


Upon further reflection, I noticed that you mentioned it's the keypress event in the question title. In that case, utilizing e.preventDefault would be beneficial, as demonstrated in another response. Simply replace your return false with this method.

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

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

How can I ensure that all row checkboxes are automatically marked as checked upon loading the Material Table in ReactJS?

I'm currently working on a project using React Material Table and I need to have the selection option pre-checked by default. Is there a way to accomplish this? function BasicSelection() { return ( <MaterialTable title="Basic Selec ...

Resetting the countdown timer is triggered when moving to a new page

In my current project, I am developing a basic battle game in which two players choose their characters and engage in combat. The battles are structured into turns, with each new turn initiating on a fresh page and featuring a timer that counts down from ...

gulp.watch executes tasks without following a specific sequence

Objective Develop a gulp.watch task to execute other tasks in a specific sequence Why this is unique While many have referred me to How to run Gulp tasks sequentially one after the other, my query differs as it pertains to using gulp.watch instead of gu ...

I am encountering the error message "Utils is not defined" while attempting to generate a chart using chart.js

Attempting to replicate the example provided in chart.js documentation : link to example Unfortunately, I am encountering the error: Uncaught ReferenceError: Utils is not defined Despite its simplicity, I am struggling to identify the issue...! ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

Creating an innovative Angular2 / Electron hybrid app that seamlessly integrates Electron API functionalities directly into the Angular2 TypeScript

I followed a tutorial on setting up an Angular2 / Electron app, which you can watch here: https://www.youtube.com/watch?v=pLPCuFFeKOU. The code base for my project is based on this repository: https://github.com/rajayogan/angular2-desktop Currently, I&ap ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

How can I post data in React/Redux while adhering to a JSON API format?

After creating a form in React and having an API with a JSON API structure that places the response within the data: [] property, I am currently using Axios and redux-thunk to fetch the data. The structure of the data from the form state is as follows: { ...

react-router version 2.0 fails to direct traffic

I'm facing an issue with a piece of code that I have modified from the react-router project page. Despite my modifications, it doesn't seem to work as expected. Configuration In my setup, I have created several simple react components: var Ind ...

White border appears when hovering over MUI TextField

I've been troubleshooting this issue for what seems like an eternity. I've combed through Chrome's inspect tool, searching for any hover styles on the fieldset element, but to no avail. Here's my dilemma... I simply want a basic outline ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Utilizing Three.js with interactive functionalities and advanced transformation controls

I'm facing an issue with my project where I am using three.interaction to capture click events on certain objects and add transformControls to them. The problem I'm encountering is that the transform controls seem to block the click event on oth ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

Incorporating Ruby on Rails tag within JavaScript

Within my html.erb file, there is an HTML button. This button is responsible for generating HTML controls and appending them to a table. Previously, everything worked smoothly without any Ruby on Rails script involved. However, now I have integrated a sele ...

Comparing OLOO and OO in ReactJS for front-end web development

After reading Kyle's book, I found it to be extremely informative. However, I am a bit perplexed by the discussion in "You Don't Know JS: this & Object Prototypes". The series argues that the "Object Linking to Other Object" design pattern is cl ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

What is the best way to merge setInterval with mouseenter events?

I have successfully implemented code that refreshes a div using ajax. However, I am looking to add functionality so that the div only refreshes every 30 seconds when the tab is active. It seems that setInterval currently refreshes the div regardless of tab ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...