LoginSignup
1
0

More than 1 year has passed since last update.

jQuery - 入力時、リアルタイムで半角に変換していく!

Last updated at Posted at 2022-05-18

答え

$(document).on('input', function(e) {
  // ① 入力内容全体を取得
  var target = $(this).val(); 

  // ② 半角に変換して上書き
  target = target.replace(/[A-Za-z0-9]/g,function(s){
    return String.fromCharCode(s.charCodeAt(0)-0xFEE0);
  }); 

  // ③ 変換したものをinputに代入し、カーソルの位置を合わせる
  var selectionStart = $(this).prop("selectionStart");
  var selectionEnd = $(this).prop("selectionEnd");
  $(this)
    .val(target)
    .attr("selectionStart", selectionStart)
    .attr("selectionEnd", selectionEnd);
})

ポイント

eventはどれを使う?

change:inputフォームからカーソルが外れたタイミングで発火

input:文字が一つでも変更されたタイミングで発火

今回は、リアルタイムで変更したかったため、inputを採用しました。
同じタイミングのeventとして、keyupがありますが、こちらだと上書きの際に古いデータまで取得してしまう(要するにうまくいかない)ので注意が必要です。

---2022/5/19 編集履歴---
カーソル位置に関するごを指摘いただき、カーソル位置を移動させない処理を追記しました

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0