【JQuery】テキストボックスで半角英数字しか入力できないようにする
テキストボックスで半角英数字しか入力できないように入力制限をかける方法です。
javascript
$(document).ready(function() { // ime-modeが使えるか var supportIMEMode = ('ime-mode' in document.body.style); // 非ASCII var noSbcRegex = /[^\x00-\x7E]+/g; // 1バイト文字専用フィールド $('.sbc_field') .on('keydown blur paste', function(e) { // ime-modeが使えるならスキップ if (e.type == 'keydown' || e.type == 'blur') if (supportIMEMode) return; // 2バイト文字が入力されたら削除 var target = $(this); if(!target.val().match(noSbcRegex)) return; window.setTimeout( function() { target.val( target.val().replace(noSbcRegex, '') ); }, 1); }); });
※cssに以下を設定する。
css
.sbc_field { ime-mode: disabled; }
コメントを残す