Leander
Leander

Reputation: 566

Move cursor to other textbox during IME-composition

I want to move the cursor to another textinput field with javascript, while the user types. When radicals are composed (korean, japanese, chinese) it causes unexpected behaviour.

E.g. if the user types in the first textbox, the cursor should be moved to the second. However, when continuing to type in the second textbox, the from the first textbox is still persistent.

[|   ]  [    ]      cursor in first box
[나   ]  [|   ]      typed 나 and cursor move
[나   ]  [난|  ]      typed ㄴ

Only typing ㄴ+ㅏ+ㄴ produces the characters 나, 난 instead of 나, ㄴ.

const a = document.getElementById("a");
const b =  document.getElementById("b");
a.oninput = e => { if (a.value == '나') b.focus(); };
<input type="text" id="a">
<input type="text" id="b">

I want to support Chrome, Safari, Firefox, Opera, Edge on Windows and MacOS.


A more extensive log.

const a = document.getElementById("a");
const b =  document.getElementById("b");
const c =  document.getElementById("c");

[a, b].forEach(el => {
  let log = e => c.textContent += `${el.id} ${event.type}: ${event.data}\n`;

  el.addEventListener("blur", log);
  el.addEventListener("keydown", log);
  el.addEventListener("compositionstart", log);
  el.addEventListener("compositionupdate", log);
  el.addEventListener("compositionend", log);
  el.addEventListener("input", log);
});

a.addEventListener("input", e => {
  if (a.value == '나') b.focus();
});
<input type="text" id="a">
<input type="text" id="b">
<br><pre type="text" id="c"></pre>

Output:

a keydown: undefined
a compositionstart: 
a compositionupdate: ㄴ
a input: ㄴ
a keydown: undefined
a compositionupdate: 나
a input: 나
a compositionend: 나
a blur: undefined
b keydown: undefined
b compositionstart: 
b compositionupdate: 난
b input: 난
// on clicking somewhere else => blurring the b field
b compositionend: 난
b blur: undefined

Upvotes: 3

Views: 839

Answers (2)

user14922462
user14922462

Reputation:

I Used Jquery to generate a cross browser solution . Tell me it works well pal !.

<input type="text" id="a">
<input type="text" id="b">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
const a = document.getElementById("a");
const b =  $("#b");
a.oninput = e => { if (a.value == 'c') b.trigger('focus'); };
</script>

Upvotes: 0

Jalaj
Jalaj

Reputation: 463

Well, it was pretty easy to do so. You just need to call blur on a.

const a = document.getElementById("a");
const b =  document.getElementById("b");
a.oninput = e => { if (a.value == '나') { b.focus();a.blur(); } };
<input type="text" id="a">
<input type="text" id="b">

Upvotes: 1

Related Questions