[[jQueryめも]]

cssで ime-mode: disabled; を指定すればInternet ExplorerやFirefoxは制御できますが、Chromeは言うことを聞いてくれません。

*方法1 [#ba43c5c3]
HTML5ではinput typeに電話番号入力欄を作成するtelが指定できます。~
数字やハイフン程度しか入力できないイメージがありますが、英字も入力できてしまいます。~
なのでこの機能を流用します。

通常はinput typeはtextでime-mode: disabled;としておく。~
Chromeであればinput typeをtelに変更してしまう。

 <style>
 #username {
     ime-mode: disabled;
 }
 </style>
 <script>
 $(function() {
     var agent = window.navigator.userAgent.toLowerCase();
     if (agent.indexOf('chrome') != -1) {
         document.getElementById('username').type = 'tel';
     }
 });
 </script>
 
 <form method="post" action="/">
 <input type="text" name="username" id="username">
 <input type="submit" value="送信">
 </form>

*方法2 [#n5bab678]
classにalphanumericを指定し、JavaScriptにて全角から半角へ変換を行います。

 $(function() {
     $('.alphanumeric').css('ime-mode', 'disabled');
 
     $('.alphanumeric').on('keyup', function(){
         var halfVal = this.value.replace(/[!-〜]/g,
         function(tmpStr) {
             return String.fromCharCode(tmpStr.charCodeAt(0) - 0xFEE0);
         });
 
         this.value = halfVal.replace(/”/g, "\"")
             .replace(/’/g, "'")
             .replace(/‘/g, "`")
             .replace(/¥/g, "\\")
             .replace(/ /g, " ")
             .replace(/&#12316;/g, "~");
     });
 });


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS