0

Initially If I type 'cde' on the input field, it will be converted to 'CDE'.
then If I type 'A' in front of the 'CDE', it will be converted to 'ACDE'.
but cursor will be moved to the end of the input field.
however, I want to keep the cursor position end of the 'A'.
How can I do that?

I am using antd Form.Item and Input component.

Here is codesandbox line:
https://codesandbox.io/s/divine-dream-2xrzst?file=/src/App.tsx

import React from "react";
import { Form, Input } from "antd";

const MyInputComponent: React.FC = () => {
  return (
    <Form.Item name="input" label="Input">
      <Input onInput={toUpperCase} />
    </Form.Item>
  );
};

export default MyInputComponent;

const toUpperCase = (
  event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
  const value = (event.target as HTMLInputElement).value;

  if (typeof value !== "string") return;

  (event.target as HTMLInputElement).value = value.toUpperCase();
};

Mamunur Rashid
  • 1,095
  • 17
  • 28
  • 1
    Does this answer your question? [Stop cursor from jumping to end of input field in javascript replace](https://stackoverflow.com/questions/8219639/stop-cursor-from-jumping-to-end-of-input-field-in-javascript-replace) – DBS Jun 21 '23 at 09:30

1 Answers1

2

WHile using the onInput method you can utilise selectionStart, selectionEnd & setSelectionRange() to get the current cursor position and keep it there after the text has changed to uppercase.

import "./styles.css";
import React from "react";
import { Form, Input } from "antd";

const toUpperCase = (
  event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
  const start = event.currentTarget.selectionStart;
  const end = event.currentTarget.selectionEnd;
  const value = (event.target as HTMLInputElement).value;

  if (typeof value !== "string") return;

  (event.target as HTMLInputElement).value = value.toUpperCase();
  event.currentTarget.setSelectionRange(start, end);
};

export default function App() {
  return (
    <Form.Item name="input" label="Input">
      <Input onInput={toUpperCase} />
    </Form.Item>
  );
}

Jake
  • 120
  • 1
  • 7