2012年12月21日金曜日

html5のrequired属性の背景色を変更

html5のクライアントバリデーションの必須属性(required属性)の背景色をjqueryを使用して変更する方法。

  (function ($) {
    $('input:required').each(function() {
      var $this = $(this);
      // 初期表示時の色設定
      changeColor($this);

      // チェンジイベントをトリガーとする色設定
      $this.change(function() {
        changeColor($this);
      });

      function changeColor(element) {
        var backgroundColor;
        if (element.val()) {
          // 値がある場合は背景色を白に
          backgroundColor = 'white';
        } else {
          // 値がない場合は背景色をピンクに
          backgroundColor = 'pink';
        }
        element.css({backgroundColor: backgroundColor});
      }
    });
  })(jQuery);