LoginSignup
1
0

More than 1 year has passed since last update.

【JavaScript ✖︎ WordPress】Ultimate Memberで作成されたフォームをVanilla JSで制御

Posted at

概要

Ultimate MemberというWordPressのプラグインがあり、会員サイトを楽に構築が出来る様になります。
「フォーム」で入力するフォームを作成する際、繰り返しフィールドの様な仕様をJavaScriptで作成してみたので記事にしてみました。

手法(管理画面)

入力するフィールドを作成。
Text Boxで作成ならinputのtypeはtext、Textareaで作成の場合はtextareaになります。
MAX値で入力してください。
本記事はText Boxでの作成、20個の場合の仕様で処理しております。

プラスボタンを作る
Content Blockにてボタンを作成する。

<button id="Button" type="button">+</button>

空の入力フィールドが沢山並んでいるのは、あまりきれいではないですよね。
入力する時は、5個ずつ表示させて、もっと必要な際はボタンを押してもらう仕様にしたいなって時。

■JavaScript

window.addEventListener('load', function() {
  const target = document.querySelector('._um_row_1'); // 自動生成された親要素のクラス
  const targetClass = document.querySelector('._um_row_1').classList;
  const targetText = target.querySelectorAll('.um-col-1 > .um-field-text'); // Text Boxの場合
  let count = "";

  // 入力がある場合の取得
  for (let i = 0; i < targetText.length; i++) {
    const elementText = targetText[i];
    const targetInput = elementText.querySelectorAll('.um-col-1 > .um-field-text > div > input');
    for (let j = 0; j < targetInput.length; j++) {
    const elementsInput = targetInput[j];
      if (elementsInput.value.length === 0) {
        count++;
      }
    }
  }

  if (count > 14) {
    target.classList.add('is-show15');
  } else if (count > 9) {
    target.classList.add('is-show10');
  } else if (count > 4) {
    target.classList.add('is-show5');
  } else if (count > 1) {
    target.classList.add('is-show1');
    document.getElementById('Button').style.display = "none";
  } else {
    document.getElementById('Button').style.display = "none";
  }

  document.querySelector('#Button').addEventListener('click', e => {
    if (target.classList.contains('is-show15') == true) {
      target.classList.remove('is-show15');
      target.classList.add('is-show10');
    } else if (target.classList.contains('is-show10') == true) {
      target.classList.remove('is-show10');
      target.classList.add('is-show5');
    } else if (target.classList.contains('is-show5') == true) {
      target.classList.remove('is-show5');
      document.getElementById('Button').style.display = "none";
    }
  });
});

■CSS

._um_row_1.is-show15 > div > div:nth-of-type(n+6) {
  display: none;
}
._um_row_1.is-show10 > div > div:nth-of-type(n+11) {
  display: none;
}
._um_row_1.is-show5 > div > div:nth-of-type(n+16) {
  display: none;
}

#Button {
  cursor: pointer;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0