javascript - Change input to uppercase without the cursor jumping to the end of the text - Stack Overflow

I'm using the following code to change my input value to uppercase:<script>function upperca

I'm using the following code to change my input value to uppercase:

<script>
function uppercase(z){
    v = z.value.toUpperCase();
    z.value = v;
}
</script>

<input type="text" id="example" onkeyup="uppercase(this)">

The problem is that when I type something in the middle of the text, the cursor jumps to the end of it. Searching on Google I tried to following code but it didn't work at all:

function uppercase(z){
    document.getElementById(z).addEventListener('input', function (e) {
      var target = e.target, position = target.selectionStart; // Capture initial position
      target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.

      v = z.value.toUpperCase();
      z.value = v;

      target.selectionEnd = position; // Set the cursor back to the initial position.
    });
}

The first code is working fine, but I still don't know how to prevent the cursor from jumping.

I'm using the following code to change my input value to uppercase:

<script>
function uppercase(z){
    v = z.value.toUpperCase();
    z.value = v;
}
</script>

<input type="text" id="example" onkeyup="uppercase(this)">

The problem is that when I type something in the middle of the text, the cursor jumps to the end of it. Searching on Google I tried to following code but it didn't work at all:

function uppercase(z){
    document.getElementById(z).addEventListener('input', function (e) {
      var target = e.target, position = target.selectionStart; // Capture initial position
      target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.

      v = z.value.toUpperCase();
      z.value = v;

      target.selectionEnd = position; // Set the cursor back to the initial position.
    });
}

The first code is working fine, but I still don't know how to prevent the cursor from jumping.

Share Improve this question asked Jan 21, 2019 at 16:19 DoceAzedoDoceAzedo 3615 silver badges16 bronze badges 1
  • 1 input { text-transform: uppercase } – Andreas Commented Jan 21, 2019 at 16:20
Add a ment  | 

4 Answers 4

Reset to default 5

You can also set the cursor position onkeyup (or whatever you are using, as long you get a reference to the input element)

function withSelectionRange() {
  const elem = document.getElementById('working');
  // get start position and end position, in case of an selection these values
  // will be different
  const startPos = elem.selectionStart;
  const endPos = elem.selectionEnd;
  elem.value = elem.value.toUpperCase();
  elem.setSelectionRange(startPos, endPos);
}

function withoutSelectionRange() {
  const elem = document.getElementById('notWorking');
  elem.value = elem.value.toUpperCase();
}
<div style="display: flex; flex-direction: column">
  <label for='working'>Uppercase text with selection range</label>
  <input id='working' type='text' onkeyup="withSelectionRange()"></input>

  <label for='notWorking'>Uppercase text input without selection range</label>
  <input id='notWorking' type='text' onkeyup="withoutSelectionRange()"></input>
</div>

Link to codepen

You can achieve this by simply adding some CSS styling:

#example {
    text-transform: uppercase;
}

This will make all the letters in the input field appear as uppercase, but the value would still be the same. If you need the value to be uppercase, transform it to uppercase the moment you need it (right before a submit for example)

I have been searching hours after hours for an solution for this same issue.

Adding CSS did the trick for me, except there is a specific requirement that our backend api only accepts upper-cased string.

So besides:

#example {
    text-transform: uppercase;
}

I also added callbacks that listen to onBlur and keydown.enter and converts the input value to upper case when those events get triggered.


P.S.:
No sample code as I'm just sharing my thoughts for people who had the same headaches and doesn't want to hack on HTMLInputElement.setSelectionRange.

The best way is to create a directive in a new file

import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import {
  Directive,
  ElementRef,
  HostListener,
  Renderer2,
  forwardRef,
} from '@angular/core';

@Directive({
  selector: 'input[toUppercase]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => UpperCaseInputDirective),
    },
  ],
})
export class UpperCaseInputDirective extends DefaultValueAccessor {
  @HostListener('keyup', ['$event']) input($event: InputEvent) {//keyup yesssss sa
    const target = $event.target as HTMLInputElement;
    const start = target.selectionStart;

    target.value = target.value.toUpperCase();
    target.setSelectionRange(start, start);

    this.onChange(target.value);
  }

  constructor(renderer: Renderer2,
              elementRef: ElementRef) {
    super(renderer, elementRef, false);
  }
}

in the app.module.ts

@NgModule({
    declarations: [
        UpperCaseInputDirective,

in your html ponent

<input  toUppercase>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742417530a4440031.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信