jqueryでフォームの有効・無効化

登録フォームと確認画面を1ファイルでまとめたい。HTMLの変更は出来る限り無しで。

作成日:2018-03-30, 更新日:2018-03-30

基本

・textareaはreadonly
・inputで「radio・checkbox・submit・file」以外はreadonly
・type=fileはクリック無効化(クリックできるけど無効・・・見た目を変更しないとダメっぽい)
・type=radioは対象以外をdisabled
・selectタグは対象以外をdisabled
・type=checkboxが全てdisabled。対象のみhidden追加。あとで削除することも考える
※resetは個人的に使わないので、対象外
※focusは気にしていない。

<style>
.confirmItem {
	border: none!important;
	/* background-color: transparent!important; */
	background-color: #f3f3f3!important;
}
</style>
<script>
var wrapForm = 対象のフォーム(IDか何か);

var switchConfirm = function(wrapForm, isInput) {
  
  $(wrapForm).find('.confirmItem').removeClass('confirmItem');
  
  // textareaはreadonly
  $(wrapForm).find('textarea').prop('readonly', isInput);
  if ( isInput ) {
    $(wrapForm).find('textarea').addClass('confirmItem');
  }
  
  // inputで「radio・checkbox・submit・file」以外はreadonly
  $(wrapForm + ' input').each(function(){
    var tmpType = $(this).attr('type');
    if ( tmpType!='radio' && tmpType!='checkbox' && tmpType!='submit' && tmpType!='file' ) {
      $(this).prop('readonly', isInput);
      if ( isInput ) {
        $(this).addClass('confirmItem');
      }
    }
  });
  
  // type=fileはclickイベント無効化
  if ( isInput ) {
    $(wrapForm).on('click', '[type=file]', function(){ return false; });
  }
  else {
    $(wrapForm).off('click', '[type=file]');
  }
  
  // type=radioは対象以外をdisabled
  $(wrapForm + ' [type=radio]').each(function(){
    if ( !$(this).prop('checked') ) {
      $(this).prop('disabled', isInput);
      if ( isInput ) {
        $(this).addClass('confirmItem');
      }
    }
  });
  
  // selectタグは対象以外をdisabled
  $(wrapForm + ' select option').each(function(){
    if ( !$(this).prop('selected') ) {
      $(this).prop('disabled', isInput);
      if ( isInput ) {
        $(this).addClass('confirmItem');
      }
    }
  });
  
  // type=checkboxが全てdisabled。対象のみhidden追加。あとで削除することも考える
  $(wrapForm + ' [type=checkbox]').each(function(){
    if ( $(this).prop('checked') ) {
      if ( isInput ) {
        var tmpChk = '<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).val() + '" class="tmpAddChkBox" />';
        $(wrapForm).append(tmpChk);
        
        $(this).addClass('confirmItem');
      }
      else {
        $(wrapForm).find('.tmpAddChkBox').remove();
      }
    }
    
    $(this).prop('disabled', isInput);
  });
  
}

$(wrapForm).on('click', 確認ボタン, functiojn(){
  switchConfirm(wrapForm, true); // 確認ボタンが押されたらすべて無効化
});

$(wrapForm).on('click', 修正ボタン, functiojn(){
  switchConfirm(wrapForm, false); // 修正ボタンが押されたらすべて有効化
});
</script>

関連項目

formのcheckboxやradio、selectのreadonly