イベント処理をクラスにまとめる

by rough cheap

HTML

<form>
  <p>ここにテキストを入力</p>
  <p><input type="text" id="txt" name="txt" size="40"></p>
  <p><span id="msg" class="readonly">&nbsp;</span>
  </p>
  <br>
  <br>
  <br>
  <p>読み取り専用</p>
  <p><input type="text" class="readonly" id="copy" name="copy" size="40" readonly="readonly"></p>

</form>

CSS

.readonly {
  background-color: #e6e6e6;
}

input[type=text] {
  border: solid 1px #bbb;
  padding: 5px;
}

JavaScript

var $txt = $("#txt");
var $copy = $("#copy");
var $msg = $("#msg");

var InpHelper = function() {
  // 非Ascii
  var noSbcRegex = /[^\x00-\x7e]+/g;
  if (!(this instanceof InpHelper)) {
    return new InpHelper();
  }

  this.selectOnFocus = function(e) {
    e.target.select();
  }

  this.textUpdated = function(e) {
    if (!$(e.target).val().match(noSbcRegex)) {
      return;
    }
    console.log("mutibyte string detected..");
    window.setTimeout(function() {
      $(e.target).val($(e.target).val().replace(noSbcRegex, ''));
    }, 1);
  }

  this.keyPressed = function(e) {
    console.log(e.type + ", " + e.which);
    if (e.which >= 37 && e.which <= 40) return;
    if (e.which >= 48 && e.which <= 57) return;
    if (e.which >= 96 && e.which <= 105) return;
    if (e.which == 8 || e.which == 0 || e.which == 9 || e.which == 46) return;
    console.log("key canceled.");
    return false;
  }
}

var helper = new InpHelper();

$txt.on('input', helper.textUpdated);
$txt.on('keypress', helper.keyPressed);
$txt.on('focus', helper.selectOnFocus);


function copyText() {
  console.log("input");
  $copy.val($txt.val());
}