Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start inside the text box.

The goal is to have the insertion point placed on the third line upon button press so that users can immediately begin typing without the need to manually click inside the text area. The styling is done using Tailwind CSS.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tailwind</title>
</head>

<body class="bg-gray-100">

  <div class="container font-sans bg-white mx-auto px-4 py-4 rounded shadow-md">

    <form action="" method="" class="form grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
      <div class="text-lg w-full underline font-bold col-span-1 sm:col-span-2 md:col-span-3 lg:col-span-4">
        <h1>Notification Information</h1>
      </div>

      <div class="Date Received space-y-4">
        ...

const monthNames = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];

var today = new Date();
var civilianToday = new Date();
var time = today.getHours() + ":" + today.getMinutes();
...
function setPosition() {
  var txtarea = document.getElementById("script");
  ...

Answer №1

How about trying this:

button.addEventListener('click',()=>{
    let position=textarea.value.search(/(?<=(.*?\n){3})./);
    textarea.setSelectionRange(position,position);
    textarea.setRangeText('text to be added\n');
});

This code snippet utilizes regular expressions to locate the character following the 3rd '\n' newline and then uses setSelectionRange to adjust the cursor position accordingly.

You can find more information on the syntax at https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

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

A handy hack for eluding XSS attacks

Recently, I found out that my html/php website is susceptible to XSS attacks. Is there a method to clean my data other than having to manually include `htmlspecialchars` for every variable sent to the webpage (there's a chance of missing some and stil ...

Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function? const hashPassword = async password => await bcrypt.ha ...

The functionality of the custom file upload button is experiencing issues on Microsoft Edge

I've been working on creating a unique custom image upload button that functions perfectly in Chrome, Firefox, and Opera based on my testing. However, I'm facing an issue where it doesn't work properly in Microsoft Edge. Feel free to check ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

Combining AngularJS with ng file upload and Sails JS for seamless file uploading

When I upload a file, I also need to send some additional information along with it. The instructions mention using the data parameter for this purpose, but I'm having trouble accessing it in my Sails controller action. Frontend: Upload.upload({ url ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Switch up the text inside a div using jQuery

I am developing a small grocery shopping application. My goal is to create a page where users can view the contents of their shopping cart by clicking a button. I have designed a template that displays the contents in a white space. The idea is to store ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

Tips on navigating the scroller vertically as the user interacts with a selected div by scrolling up and down

On my webpage, I have various div elements displayed. Each div has the options to move it up or down using the buttons labeled "UP" and "Down". When a user selects a div, they can then use these buttons to adjust its position. I am looking for a way to au ...

How to handle JavaScript exceptions when encountering a null JSON value?

I am receiving data in JSON format using AJAX from an action in Struts 2 for my view. The data consists of a set of information. For example: {"home": "1234", "room": null} When I try to read data.home, I successfully get the value 1234. However, when a ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

Can an icon be included in Material UI's DataGrid headers when the sorting direction is not defined?

In the DataGrid's API of Material UI, you can see how to include a sort icon for ascending and descending directions. By default, these icons are shown as arrow up and arrow down symbols but can be customized using props. However, my project requires ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

Utilizing Javascript Conditional for Substitution

Currently, I have a JavaScript function that replaces all links with registration messages: <script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...

Styling content in a CSS file and then rendering it as a

My current project involves converting a webpage into a PDF file and I am using @page @bottom-left to insert text in the bottom left corner. @page {size: portrait A4; @bottom-left {content: "Some text to display at the bottom left. Some additional text ...

Using AngularJS to automatically include predefined data in an $http request

I am looking for a way to include a default data attribute in an http request. I came up with the following code: var app = angular.module('dumbhttp', []); app.service('dumbhttp', function ($http, $location) { this.post = function ...