MTAppjQuery を使ってコンテンツタイプの日付フィールドの初期値を「今日」にする

MTAppjQuery を使ってコンテンツデータの日付フィールドのデフォルトを新規作成する日にする方法をご紹介します。

この記事は弊社 bit part 合同会社が提供している Movable Type プラグイン「MTAppjQuery」の利用を前提としております。MTAppjQuery って何?という方は弊社の「MTAppjQuery」の製品ページをご覧ください。

先ほど、MT Hub の質問コーナーで「日付フィールドのデフォルトを「今日」にしたい」という投稿をみました。

弊社のプラグイン「MTAppjQuery」をご利用いただいている場合に限りますが、簡単に実現できますので、その方法をご紹介します。

まず、user.js に以下の setCurrentDateTimeIfEmpty という関数を定義します。

function setCurrentDateTimeIfEmpty(fieldName) {
    if (!fieldName) {
        alert('fieldNameは必須です');
    }
    const id = mtapp.getContentFieldIdByLabel(fieldName);
    if (!id) {
        return;
    }
    const dateField = document.querySelector(`[name="date-${id}"]`);
    const timeField = document.querySelector(`[name="time-${id}"]`);
    const now = new Date();

    if (dateField && !dateField.value) {
        dateField.value = now.toISOString().slice(0, 10);
    }

    if (timeField && !timeField.value) {
        timeField.value = now.toTimeString().slice(0, 8);
    }
}

そして「開催日」という名前の日付フィールドに適用したい場合は、user.js の上記の関数より下で以下のようにして実行します。

setCurrentDateTimeIfEmpty('開催日');

これで「開催日」というフィールドが空の時、つまり新規作成の時だけ、今日の日付がセットされるようになります。

なお、上記の関数は「日付と時刻」「日付」「時刻」の3つのタイプのフィールドに使うことができます。

Clean Shot 2025 03 21 at 14 31 27 2x
Published 2025-03-21
Updated 2025-03-21

⚡️ 話題の一冊 ⚡️

「MTAppjQuery」カテゴリの記事一覧